OpenCVModule.cmake 49.1 KB
Newer Older
1 2 3 4 5 6 7 8
# Local variables (set for each module):
#
# name       - short name in lower case i.e. core
# the_module - full name in lower case i.e. opencv_core

# Global variables:
#
# OPENCV_MODULE_${the_module}_LOCATION
Alexander Alekhin's avatar
Alexander Alekhin committed
9
# OPENCV_MODULE_${the_module}_BINARY_DIR
10
# OPENCV_MODULE_${the_module}_DESCRIPTION
11
# OPENCV_MODULE_${the_module}_CLASS - PUBLIC|INTERNAL|BINDINGS
12 13 14
# OPENCV_MODULE_${the_module}_HEADERS
# OPENCV_MODULE_${the_module}_SOURCES
# OPENCV_MODULE_${the_module}_DEPS - final flattened set of module dependencies
Alexander Alekhin's avatar
Alexander Alekhin committed
15
# OPENCV_MODULE_${the_module}_DEPS_TO_LINK - differs from above for world build only
16
# OPENCV_MODULE_${the_module}_DEPS_EXT - non-module dependencies
17 18
# OPENCV_MODULE_${the_module}_REQ_DEPS
# OPENCV_MODULE_${the_module}_OPT_DEPS
19 20
# OPENCV_MODULE_${the_module}_PRIVATE_REQ_DEPS
# OPENCV_MODULE_${the_module}_PRIVATE_OPT_DEPS
Alexander Alekhin's avatar
Alexander Alekhin committed
21
# OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD
22
# OPENCV_MODULE_${the_module}_CUDA_OBJECTS - compiled CUDA objects list
23
# OPENCV_MODULE_${the_module}_CHILDREN - list of submodules for compound modules (cmake >= 2.8.8)
24
# OPENCV_MODULE_${the_module}_WRAPPERS - list of wrappers supporting this module
25 26 27 28
# HAVE_${the_module} - for fast check of module availability

# To control the setup of the module you could also set:
# the_description - text to be used as current module description
29
# the_label - label for current module
30
# OPENCV_MODULE_TYPE - STATIC|SHARED - set to force override global settings for current module
31 32
# OPENCV_MODULE_IS_PART_OF_WORLD - ON|OFF (default ON) - should the module be added to the opencv_world?
# BUILD_${the_module}_INIT - ON|OFF (default ON) - initial value for BUILD_${the_module}
33
# OPENCV_MODULE_CHILDREN - list of submodules
34 35 36 37

# The verbose template for OpenCV module:
#
#   ocv_add_module(modname <dependencies>)
38 39
#   ocv_glob_module_sources(([EXCLUDE_CUDA] <extra sources&headers>)
#                          or glob them manually and ocv_set_module_sources(...)
40 41 42 43 44 45 46
#   ocv_module_include_directories(<extra include directories>)
#   ocv_create_module()
#   <add extra link dependencies, compiler options, etc>
#   ocv_add_precompiled_headers(${the_module})
#   <add extra installation rules>
#   ocv_add_accuracy_tests(<extra dependencies>)
#   ocv_add_perf_tests(<extra dependencies>)
47
#   ocv_add_samples(<extra dependencies>)
48 49 50 51 52 53 54 55
#
#
# If module have no "extra" then you can define it in one line:
#
#   ocv_define_module(modname <dependencies>)

# clean flags for modules enabled on previous cmake run
# this is necessary to correctly handle modules removal
56
foreach(mod ${OPENCV_MODULES_BUILD} ${OPENCV_MODULES_DISABLED_USER} ${OPENCV_MODULES_DISABLED_AUTO} ${OPENCV_MODULES_DISABLED_FORCE})
57 58 59
  if(HAVE_${mod})
    unset(HAVE_${mod} CACHE)
  endif()
60 61
  unset(OPENCV_MODULE_${mod}_DEPS CACHE)
  unset(OPENCV_MODULE_${mod}_DEPS_EXT CACHE)
62 63
  unset(OPENCV_MODULE_${mod}_REQ_DEPS CACHE)
  unset(OPENCV_MODULE_${mod}_OPT_DEPS CACHE)
64 65
  unset(OPENCV_MODULE_${mod}_PRIVATE_REQ_DEPS CACHE)
  unset(OPENCV_MODULE_${mod}_PRIVATE_OPT_DEPS CACHE)
Alexander Alekhin's avatar
Alexander Alekhin committed
66
  unset(OPENCV_MODULE_${mod}_LINK_DEPS CACHE)
Maksim Shabunin's avatar
Maksim Shabunin committed
67
  unset(OPENCV_MODULE_${mod}_WRAPPERS CACHE)
68 69 70 71 72 73 74 75
endforeach()

# clean modules info which needs to be recalculated
set(OPENCV_MODULES_PUBLIC         "" CACHE INTERNAL "List of OpenCV modules marked for export")
set(OPENCV_MODULES_BUILD          "" CACHE INTERNAL "List of OpenCV modules included into the build")
set(OPENCV_MODULES_DISABLED_USER  "" CACHE INTERNAL "List of OpenCV modules explicitly disabled by user")
set(OPENCV_MODULES_DISABLED_AUTO  "" CACHE INTERNAL "List of OpenCV modules implicitly disabled due to dependencies")
set(OPENCV_MODULES_DISABLED_FORCE "" CACHE INTERNAL "List of OpenCV modules which can not be build in current configuration")
Alexander Alekhin's avatar
Alexander Alekhin committed
76
unset(OPENCV_WORLD_MODULES CACHE)
77 78 79

# adds dependencies to OpenCV module
# Usage:
80
#   add_dependencies(opencv_<name> [REQUIRED] [<list of dependencies>] [OPTIONAL <list of modules>] [WRAP <list of wrappers>])
81 82 83
# Notes:
# * <list of dependencies> - can include full names of modules or full pathes to shared/static libraries or cmake targets
macro(ocv_add_dependencies full_modname)
Alexander Alekhin's avatar
Alexander Alekhin committed
84
  ocv_debug_message("ocv_add_dependencies(" ${full_modname} ${ARGN} ")")
85
  #we don't clean the dependencies here to allow this macro several times for every module
86 87
  foreach(d "REQUIRED" ${ARGN})
    if(d STREQUAL "REQUIRED")
88 89 90
      set(__depsvar OPENCV_MODULE_${full_modname}_REQ_DEPS)
    elseif(d STREQUAL "OPTIONAL")
      set(__depsvar OPENCV_MODULE_${full_modname}_OPT_DEPS)
91 92 93 94
    elseif(d STREQUAL "PRIVATE_REQUIRED")
      set(__depsvar OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS)
    elseif(d STREQUAL "PRIVATE_OPTIONAL")
      set(__depsvar OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS)
95 96
    elseif(d STREQUAL "WRAP")
      set(__depsvar OPENCV_MODULE_${full_modname}_WRAPPERS)
97 98 99 100
    else()
      list(APPEND ${__depsvar} "${d}")
    endif()
  endforeach()
101 102
  unset(__depsvar)

Maksim Shabunin's avatar
Maksim Shabunin committed
103 104 105 106 107 108 109 110 111
  # hack for python
  set(__python_idx)
  list(FIND OPENCV_MODULE_${full_modname}_WRAPPERS "python" __python_idx)
  if (NOT __python_idx EQUAL -1)
    list(REMOVE_ITEM OPENCV_MODULE_${full_modname}_WRAPPERS "python")
    list(APPEND OPENCV_MODULE_${full_modname}_WRAPPERS "python2" "python3")
  endif()
  unset(__python_idx)

112 113
  ocv_list_unique(OPENCV_MODULE_${full_modname}_REQ_DEPS)
  ocv_list_unique(OPENCV_MODULE_${full_modname}_OPT_DEPS)
114 115
  ocv_list_unique(OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS)
  ocv_list_unique(OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS)
116
  ocv_list_unique(OPENCV_MODULE_${full_modname}_WRAPPERS)
117 118 119 120 121 122 123 124 125

  set(OPENCV_MODULE_${full_modname}_REQ_DEPS ${OPENCV_MODULE_${full_modname}_REQ_DEPS}
    CACHE INTERNAL "Required dependencies of ${full_modname} module")
  set(OPENCV_MODULE_${full_modname}_OPT_DEPS ${OPENCV_MODULE_${full_modname}_OPT_DEPS}
    CACHE INTERNAL "Optional dependencies of ${full_modname} module")
  set(OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS ${OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS}
    CACHE INTERNAL "Required private dependencies of ${full_modname} module")
  set(OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS ${OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS}
    CACHE INTERNAL "Optional private dependencies of ${full_modname} module")
126 127
  set(OPENCV_MODULE_${full_modname}_WRAPPERS ${OPENCV_MODULE_${full_modname}_WRAPPERS}
    CACHE INTERNAL "List of wrappers supporting module ${full_modname}")
128 129
endmacro()

130 131
# declare new OpenCV module in current folder
# Usage:
132
#   ocv_add_module(<name> [INTERNAL|BINDINGS] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>] [WRAP <list of wrappers>])
133
# Example:
134
#   ocv_add_module(yaom INTERNAL opencv_core opencv_highgui opencv_flann OPTIONAL opencv_cudev)
135
macro(ocv_add_module _name)
Alexander Alekhin's avatar
Alexander Alekhin committed
136
  ocv_debug_message("ocv_add_module(" ${_name} ${ARGN} ")")
137 138
  string(TOLOWER "${_name}" name)
  set(the_module opencv_${name})
139

140 141
  # the first pass - collect modules info, the second pass - create targets
  if(OPENCV_INITIAL_PASS)
142 143 144 145 146 147 148 149
    #guard agains redefinition
    if(";${OPENCV_MODULES_BUILD};${OPENCV_MODULES_DISABLED_USER};" MATCHES ";${the_module};")
      message(FATAL_ERROR "Redefinition of the ${the_module} module.
  at:                    ${CMAKE_CURRENT_SOURCE_DIR}
  previously defined at: ${OPENCV_MODULE_${the_module}_LOCATION}
")
    endif()

150 151 152
    if(NOT DEFINED the_description)
      set(the_description "The ${name} OpenCV module")
    endif()
153

154 155
    if(NOT DEFINED BUILD_${the_module}_INIT)
      set(BUILD_${the_module}_INIT ON)
156
    endif()
157 158

    # create option to enable/disable this module
159
    option(BUILD_${the_module} "Include ${the_module} module into the OpenCV build" ${BUILD_${the_module}_INIT})
160

161 162 163 164
    # remember the module details
    set(OPENCV_MODULE_${the_module}_DESCRIPTION "${the_description}" CACHE INTERNAL "Brief description of ${the_module} module")
    set(OPENCV_MODULE_${the_module}_LOCATION    "${CMAKE_CURRENT_SOURCE_DIR}" CACHE INTERNAL "Location of ${the_module} module sources")

Alexander Alekhin's avatar
Alexander Alekhin committed
165 166
    set(OPENCV_MODULE_${the_module}_LINK_DEPS "" CACHE INTERNAL "")

167
    # parse list of dependencies
168
    if("${ARGV1}" STREQUAL "INTERNAL" OR "${ARGV1}" STREQUAL "BINDINGS")
Ilya Lavrenov's avatar
Ilya Lavrenov committed
169
      set(OPENCV_MODULE_${the_module}_CLASS "${ARGV1}" CACHE INTERNAL "The category of the module")
170 171 172 173
      set(__ocv_argn__ ${ARGN})
      list(REMOVE_AT __ocv_argn__ 0)
      ocv_add_dependencies(${the_module} ${__ocv_argn__})
      unset(__ocv_argn__)
174
    else()
Ilya Lavrenov's avatar
Ilya Lavrenov committed
175
      set(OPENCV_MODULE_${the_module}_CLASS "PUBLIC" CACHE INTERNAL "The category of the module")
176 177
      ocv_add_dependencies(${the_module} ${ARGN})
      if(BUILD_${the_module})
178 179
        set(OPENCV_MODULES_PUBLIC ${OPENCV_MODULES_PUBLIC} "${the_module}" CACHE INTERNAL "List of OpenCV modules marked for export")
      endif()
180
    endif()
181

182
    # add self to the world dependencies
183 184
    if((NOT DEFINED OPENCV_MODULE_IS_PART_OF_WORLD
        AND NOT OPENCV_MODULE_${the_module}_CLASS STREQUAL "BINDINGS"
185 186
        AND NOT OPENCV_PROCESSING_EXTRA_MODULES
        AND (NOT BUILD_SHARED_LIBS OR NOT "x${OPENCV_MODULE_TYPE}" STREQUAL "xSTATIC"))
Alexander Alekhin's avatar
Alexander Alekhin committed
187 188 189
        OR OPENCV_MODULE_IS_PART_OF_WORLD
        )
      set(OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD ON CACHE INTERNAL "")
190
      ocv_add_dependencies(opencv_world OPTIONAL ${the_module})
Alexander Alekhin's avatar
Alexander Alekhin committed
191 192
    else()
      set(OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD OFF CACHE INTERNAL "")
193
    endif()
194

195 196 197 198 199 200 201 202 203
    if(NOT DEFINED the_label)
      if(OPENCV_PROCESSING_EXTRA_MODULES)
        set(the_label "Extra")
      else()
        set(the_label "Main")
      endif()
    endif()
    set(OPENCV_MODULE_${the_module}_LABEL "${the_label};${the_module}" CACHE INTERNAL "")

204
    if(BUILD_${the_module})
205
      set(OPENCV_MODULES_BUILD ${OPENCV_MODULES_BUILD} "${the_module}" CACHE INTERNAL "List of OpenCV modules included into the build")
206 207
    else()
      set(OPENCV_MODULES_DISABLED_USER ${OPENCV_MODULES_DISABLED_USER} "${the_module}" CACHE INTERNAL "List of OpenCV modules explicitly disabled by user")
208
    endif()
209

210 211
    # add submodules if any
    set(OPENCV_MODULE_${the_module}_CHILDREN "${OPENCV_MODULE_CHILDREN}" CACHE INTERNAL "List of ${the_module} submodules")
212

213 214 215 216 217
    # add reverse wrapper dependencies
    foreach (wrapper ${OPENCV_MODULE_${the_module}_WRAPPERS})
      ocv_add_dependencies(opencv_${wrapper} OPTIONAL ${the_module})
    endforeach()

218
    # stop processing of current file
219
    return()
Alexander Alekhin's avatar
Alexander Alekhin committed
220 221
  else()
    set(OPENCV_MODULE_${the_module}_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE INTERNAL "")
222
    if(NOT BUILD_${the_module})
223
      return() # extra protection from redefinition
224
    endif()
Alexander Alekhin's avatar
Alexander Alekhin committed
225 226 227 228
    if((NOT OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD AND NOT ${the_module} STREQUAL opencv_world) OR NOT ${BUILD_opencv_world})
      project(${the_module})
    endif()
  endif()
229 230
endmacro()

231
# excludes module from current configuration
232 233 234 235 236 237 238
macro(ocv_module_disable module)
  set(__modname ${module})
  if(NOT __modname MATCHES "^opencv_")
    set(__modname opencv_${module})
  endif()
  list(APPEND OPENCV_MODULES_DISABLED_FORCE "${__modname}")
  set(HAVE_${__modname} OFF CACHE INTERNAL "Module ${__modname} can not be built in current configuration")
239
  set(OPENCV_MODULE_${__modname}_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}" CACHE INTERNAL "Location of ${__modname} module sources")
240
  set(OPENCV_MODULES_DISABLED_FORCE "${OPENCV_MODULES_DISABLED_FORCE}" CACHE INTERNAL "List of OpenCV modules which can not be build in current configuration")
241 242 243
  if(BUILD_${__modname})
    # touch variable controlling build of the module to suppress "unused variable" CMake warning
  endif()
244
  unset(__modname)
245
  return() # leave the current folder
246
endmacro()
247 248


249 250 251
# collect modules from specified directories
# NB: must be called only once!
macro(ocv_glob_modules)
252 253 254 255 256
  if(DEFINED OPENCV_INITIAL_PASS)
    message(FATAL_ERROR "OpenCV has already loaded its modules. Calling ocv_glob_modules second time is not allowed.")
  endif()
  set(__directories_observed "")

257
  # collect modules
258
  set(OPENCV_INITIAL_PASS ON)
Alexander Alekhin's avatar
Alexander Alekhin committed
259
  set(OPENCV_PROCESSING_EXTRA_MODULES 0)
260
  foreach(__path ${ARGN})
Alexander Alekhin's avatar
Alexander Alekhin committed
261 262
    if("${__path}" STREQUAL "EXTRA")
      set(OPENCV_PROCESSING_EXTRA_MODULES 1)
263 264
    else()
      get_filename_component(__path "${__path}" ABSOLUTE)
265

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
      list(FIND __directories_observed "${__path}" __pathIdx)
      if(__pathIdx GREATER -1)
        message(FATAL_ERROR "The directory ${__path} is observed for OpenCV modules second time.")
      endif()
      list(APPEND __directories_observed "${__path}")

      set(__count 0)
      file(GLOB __ocvmodules RELATIVE "${__path}" "${__path}/*")
      if(__ocvmodules)
        list(SORT __ocvmodules)
        foreach(mod ${__ocvmodules})
          get_filename_component(__modpath "${__path}/${mod}" ABSOLUTE)
          if(EXISTS "${__modpath}/CMakeLists.txt")

            list(FIND __directories_observed "${__modpath}" __pathIdx)
            if(__pathIdx GREATER -1)
              message(FATAL_ERROR "The module from ${__modpath} is already loaded.")
            endif()
            list(APPEND __directories_observed "${__modpath}")

            add_subdirectory("${__modpath}" "${CMAKE_CURRENT_BINARY_DIR}/${mod}/.${mod}")

            if (DEFINED OPENCV_MODULE_opencv_${mod}_LOCATION)
              math(EXPR __count "${__count} + 1")
            endif()
291
          endif()
292 293 294 295 296
        endforeach()
      endif()
      if (OPENCV_PROCESSING_EXTRA_MODULES AND ${__count} LESS 1)
        message(SEND_ERROR "No extra modules found in folder: ${__path}\nPlease provide path to 'opencv_contrib/modules' folder.")
      endif()
297
    endif()
298
  endforeach()
299
  ocv_clear_vars(__ocvmodules __directories_observed __path __modpath __pathIdx)
300

301
  # resolve dependencies
302
  __ocv_resolve_dependencies()
303

304
  # create modules
305
  set(OPENCV_INITIAL_PASS OFF PARENT_SCOPE)
306
  set(OPENCV_INITIAL_PASS OFF)
Alexander Alekhin's avatar
Alexander Alekhin committed
307 308
  if(${BUILD_opencv_world})
    foreach(m ${OPENCV_MODULES_BUILD})
309 310 311
      if("${m}" STREQUAL opencv_world)
        add_subdirectory("${OPENCV_MODULE_opencv_world_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/world")
      elseif(NOT OPENCV_MODULE_${m}_IS_PART_OF_WORLD AND NOT ${m} STREQUAL opencv_world)
Alexander Alekhin's avatar
Alexander Alekhin committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        message(STATUS "Processing module ${m}...")
        if(m MATCHES "^opencv_")
          string(REGEX REPLACE "^opencv_" "" __shortname "${m}")
          add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${__shortname}")
        else()
          message(WARNING "Check module name: ${m}")
          add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${m}")
        endif()
      endif()
    endforeach()
  else()
    foreach(m ${OPENCV_MODULES_BUILD})
      if(m MATCHES "^opencv_")
        string(REGEX REPLACE "^opencv_" "" __shortname "${m}")
        add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${__shortname}")
      else()
        message(WARNING "Check module name: ${m}")
        add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${m}")
      endif()
    endforeach()
  endif()
333
  unset(__shortname)
334 335
endmacro()

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

# disables OpenCV module with missing dependencies
function(__ocv_module_turn_off the_module)
  list(REMOVE_ITEM OPENCV_MODULES_DISABLED_AUTO "${the_module}")
  list(APPEND OPENCV_MODULES_DISABLED_AUTO "${the_module}")
  list(REMOVE_ITEM OPENCV_MODULES_BUILD "${the_module}")
  list(REMOVE_ITEM OPENCV_MODULES_PUBLIC "${the_module}")
  set(HAVE_${the_module} OFF CACHE INTERNAL "Module ${the_module} can not be built in current configuration")

  set(OPENCV_MODULES_DISABLED_AUTO "${OPENCV_MODULES_DISABLED_AUTO}" CACHE INTERNAL "")
  set(OPENCV_MODULES_BUILD "${OPENCV_MODULES_BUILD}" CACHE INTERNAL "")
  set(OPENCV_MODULES_PUBLIC "${OPENCV_MODULES_PUBLIC}" CACHE INTERNAL "")
endfunction()

# sort modules by dependencies
function(__ocv_sort_modules_by_deps __lst)
  ocv_list_sort(${__lst})
353 354
  set(input ${${__lst}})
  set(result "")
355
  set(result_extra "")
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  while(input)
    list(LENGTH input length_before)
    foreach (m ${input})
      # check if module is in the result already
      if (NOT ";${result};" MATCHES ";${m};")
        # scan through module dependencies...
        set(unresolved_deps_found FALSE)
        foreach (d ${OPENCV_MODULE_${m}_CHILDREN} ${OPENCV_MODULE_${m}_DEPS})
          # ... which are not already in the result and are enabled
          if ((NOT ";${result};" MATCHES ";${d};") AND HAVE_${d})
            set(unresolved_deps_found TRUE)
            break()
          endif()
        endforeach()
        # chek if all dependencies for this module has been resolved
        if (NOT unresolved_deps_found)
          list(APPEND result ${m})
          list(REMOVE_ITEM input ${m})
374 375 376
        endif()
      endif()
    endforeach()
377 378 379
    list(LENGTH input length_after)
    # check for infinite loop or unresolved dependencies
    if (NOT length_after LESS length_before)
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
      if(NOT BUILD_SHARED_LIBS)
        if (";${input};" MATCHES ";opencv_world;")
          list(REMOVE_ITEM input "opencv_world")
          list(APPEND result_extra "opencv_world")
        else()
          # We can't do here something
          list(APPEND result ${input})
          break()
        endif()
      else()
        message(FATAL_ERROR WARNING "Unresolved dependencies or loop in dependency graph (${length_after})\n"
          "Processed ${__lst}: ${${__lst}}\n"
          "Good modules: ${result}\n"
          "Bad modules: ${input}"
        )
        list(APPEND result ${input})
        break()
      endif()
398
    endif()
399
  endwhile()
400
  set(${__lst} "${result};${result_extra}" PARENT_SCOPE)
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
endfunction()

# resolve dependensies
function(__ocv_resolve_dependencies)
  foreach(m ${OPENCV_MODULES_DISABLED_USER})
    set(HAVE_${m} OFF CACHE INTERNAL "Module ${m} will not be built in current configuration")
  endforeach()
  foreach(m ${OPENCV_MODULES_BUILD})
    set(HAVE_${m} ON CACHE INTERNAL "Module ${m} will be built in current configuration")
  endforeach()

  # disable MODULES with unresolved dependencies
  set(has_changes ON)
  while(has_changes)
    set(has_changes OFF)
    foreach(m ${OPENCV_MODULES_BUILD})
      set(__deps ${OPENCV_MODULE_${m}_REQ_DEPS} ${OPENCV_MODULE_${m}_PRIVATE_REQ_DEPS})
      while(__deps)
        ocv_list_pop_front(__deps d)
420 421 422 423 424 425 426 427 428 429
        string(TOLOWER "${d}" upper_d)
        if(NOT (HAVE_${d} OR HAVE_${upper_d} OR TARGET ${d} OR EXISTS ${d}))
          if(d MATCHES "^opencv_") # TODO Remove this condition in the future and use HAVE_ variables only
            message(STATUS "Module ${m} disabled because ${d} dependency can't be resolved!")
            __ocv_module_turn_off(${m})
            set(has_changes ON)
            break()
          else()
            message(STATUS "Assume that non-module dependency is available: ${d} (for module ${m})")
          endif()
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        endif()
      endwhile()
    endforeach()
  endwhile()

#  message(STATUS "List of active modules: ${OPENCV_MODULES_BUILD}")

  foreach(m ${OPENCV_MODULES_BUILD})
    set(deps_${m} ${OPENCV_MODULE_${m}_REQ_DEPS})
    foreach(d ${OPENCV_MODULE_${m}_OPT_DEPS})
      if(NOT (";${deps_${m}};" MATCHES ";${d};"))
        if(HAVE_${d} OR TARGET ${d})
          list(APPEND deps_${m} ${d})
        endif()
      endif()
    endforeach()
#    message(STATUS "Initial deps of ${m} (w/o private deps): ${deps_${m}}")
  endforeach()

  # propagate dependencies
  set(has_changes ON)
  while(has_changes)
    set(has_changes OFF)
    foreach(m2 ${OPENCV_MODULES_BUILD}) # transfer deps of m2 to m
      foreach(m ${OPENCV_MODULES_BUILD})
        if((NOT m STREQUAL m2) AND ";${deps_${m}};" MATCHES ";${m2};")
          foreach(d ${deps_${m2}})
            if(NOT (";${deps_${m}};" MATCHES ";${d};"))
#              message(STATUS "  Transfer dependency ${d} from ${m2} to ${m}")
              list(APPEND deps_${m} ${d})
              set(has_changes ON)
            endif()
462 463 464 465 466 467 468 469 470 471 472
            if(BUILD_opencv_world
                AND NOT "${m}" STREQUAL "opencv_world"
                AND NOT "${m2}" STREQUAL "opencv_world"
                AND OPENCV_MODULE_${m2}_IS_PART_OF_WORLD
                AND NOT OPENCV_MODULE_${m}_IS_PART_OF_WORLD)
              if(NOT (";${deps_${m}};" MATCHES ";opencv_world;"))
#                message(STATUS "  Transfer dependency opencv_world alias ${m2} to ${m}")
                list(APPEND deps_${m} opencv_world)
                set(has_changes ON)
              endif()
            endif()
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
          endforeach()
        endif()
      endforeach()
    endforeach()
  endwhile()

  # process private deps
  foreach(m ${OPENCV_MODULES_BUILD})
    foreach(d ${OPENCV_MODULE_${m}_PRIVATE_REQ_DEPS})
      if(NOT (";${deps_${m}};" MATCHES ";${d};"))
        list(APPEND deps_${m} ${d})
      endif()
    endforeach()
    foreach(d ${OPENCV_MODULE_${m}_PRIVATE_OPT_DEPS})
      if(NOT (";${deps_${m}};" MATCHES ";${d};"))
        if(HAVE_${d} OR TARGET ${d})
          list(APPEND deps_${m} ${d})
        endif()
      endif()
    endforeach()
  endforeach()

  ocv_list_sort(OPENCV_MODULES_BUILD)

  foreach(m ${OPENCV_MODULES_BUILD})
#    message(STATUS "FULL deps of ${m}: ${deps_${m}}")
    set(OPENCV_MODULE_${m}_DEPS ${deps_${m}})
    set(OPENCV_MODULE_${m}_DEPS_EXT ${deps_${m}})
    ocv_list_filterout(OPENCV_MODULE_${m}_DEPS_EXT "^opencv_[^ ]+$")
    if(OPENCV_MODULE_${m}_DEPS_EXT AND OPENCV_MODULE_${m}_DEPS)
      list(REMOVE_ITEM OPENCV_MODULE_${m}_DEPS ${OPENCV_MODULE_${m}_DEPS_EXT})
    endif()
  endforeach()

  # reorder dependencies
  foreach(m ${OPENCV_MODULES_BUILD})
    __ocv_sort_modules_by_deps(OPENCV_MODULE_${m}_DEPS)

Alexander Alekhin's avatar
Alexander Alekhin committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    set(LINK_DEPS ${OPENCV_MODULE_${m}_DEPS})

    # process world
    if(BUILD_opencv_world)
      if(OPENCV_MODULE_${m}_IS_PART_OF_WORLD)
        list(APPEND OPENCV_WORLD_MODULES ${m})
      endif()
      foreach(m2 ${OPENCV_MODULES_BUILD})
        if(OPENCV_MODULE_${m2}_IS_PART_OF_WORLD)
          if(";${LINK_DEPS};" MATCHES ";${m2};")
            list(REMOVE_ITEM LINK_DEPS ${m2})
            if(NOT (";${LINK_DEPS};" MATCHES ";opencv_world;") AND NOT (${m} STREQUAL opencv_world))
              list(APPEND LINK_DEPS opencv_world)
            endif()
          endif()
          if(${m} STREQUAL opencv_world)
            list(APPEND OPENCV_MODULE_opencv_world_DEPS_EXT ${OPENCV_MODULE_${m2}_DEPS_EXT})
          endif()
        endif()
      endforeach()
    endif()

533 534
    set(OPENCV_MODULE_${m}_DEPS ${OPENCV_MODULE_${m}_DEPS} CACHE INTERNAL "Flattened dependencies of ${m} module")
    set(OPENCV_MODULE_${m}_DEPS_EXT ${OPENCV_MODULE_${m}_DEPS_EXT} CACHE INTERNAL "Extra dependencies of ${m} module")
Alexander Alekhin's avatar
Alexander Alekhin committed
535
    set(OPENCV_MODULE_${m}_DEPS_TO_LINK ${LINK_DEPS} CACHE INTERNAL "Flattened dependencies of ${m} module (for linker)")
536

Alexander Alekhin's avatar
Alexander Alekhin committed
537 538 539 540
#    message(STATUS "  module deps of ${m}: ${OPENCV_MODULE_${m}_DEPS}")
#    message(STATUS "  module link deps of ${m}: ${OPENCV_MODULE_${m}_DEPS_TO_LINK}")
#    message(STATUS "  extra deps of ${m}: ${OPENCV_MODULE_${m}_DEPS_EXT}")
#    message(STATUS "")
541 542 543 544 545 546 547
  endforeach()

  __ocv_sort_modules_by_deps(OPENCV_MODULES_BUILD)

  set(OPENCV_MODULES_PUBLIC        ${OPENCV_MODULES_PUBLIC}        CACHE INTERNAL "List of OpenCV modules marked for export")
  set(OPENCV_MODULES_BUILD         ${OPENCV_MODULES_BUILD}         CACHE INTERNAL "List of OpenCV modules included into the build")
  set(OPENCV_MODULES_DISABLED_AUTO ${OPENCV_MODULES_DISABLED_AUTO} CACHE INTERNAL "List of OpenCV modules implicitly disabled due to dependencies")
Alexander Alekhin's avatar
Alexander Alekhin committed
548
  set(OPENCV_WORLD_MODULES         ${OPENCV_WORLD_MODULES}         CACHE INTERNAL "List of OpenCV modules included into the world")
549 550 551
endfunction()


552 553 554 555 556
# setup include paths for the list of passed modules
macro(ocv_include_modules)
  foreach(d ${ARGN})
    if(d MATCHES "^opencv_" AND HAVE_${d})
      if (EXISTS "${OPENCV_MODULE_${d}_LOCATION}/include")
557
        ocv_include_directories("${OPENCV_MODULE_${d}_LOCATION}/include")
558 559
      endif()
    elseif(EXISTS "${d}")
560
      ocv_include_directories("${d}")
561 562 563
    endif()
  endforeach()
endmacro()
564

Maksim Shabunin's avatar
Maksim Shabunin committed
565 566 567 568 569 570 571 572 573 574 575 576
# same as previous but with dependencies
macro(ocv_include_modules_recurse)
  ocv_include_modules(${ARGN})
  foreach(d ${ARGN})
    if(d MATCHES "^opencv_" AND HAVE_${d} AND DEFINED OPENCV_MODULE_${d}_DEPS)
      foreach (sub ${OPENCV_MODULE_${d}_DEPS})
        ocv_include_modules(${sub})
      endforeach()
    endif()
  endforeach()
endmacro()

Alexander Alekhin's avatar
Alexander Alekhin committed
577 578 579 580 581 582 583 584 585 586 587 588 589
# setup include paths for the list of passed modules
macro(ocv_target_include_modules target)
  foreach(d ${ARGN})
    if(d MATCHES "^opencv_" AND HAVE_${d})
      if (EXISTS "${OPENCV_MODULE_${d}_LOCATION}/include")
        ocv_target_include_directories(${target} "${OPENCV_MODULE_${d}_LOCATION}/include")
      endif()
    elseif(EXISTS "${d}")
      ocv_target_include_directories(${target} "${d}")
    endif()
  endforeach()
endmacro()

590
# setup include paths for the list of passed modules and recursively add dependent modules
Alexander Alekhin's avatar
Alexander Alekhin committed
591
macro(ocv_target_include_modules_recurse target)
592 593 594
  foreach(d ${ARGN})
    if(d MATCHES "^opencv_" AND HAVE_${d})
      if (EXISTS "${OPENCV_MODULE_${d}_LOCATION}/include")
Alexander Alekhin's avatar
Alexander Alekhin committed
595
        ocv_target_include_directories(${target} "${OPENCV_MODULE_${d}_LOCATION}/include")
596 597
      endif()
      if(OPENCV_MODULE_${d}_DEPS)
Alexander Alekhin's avatar
Alexander Alekhin committed
598
        ocv_target_include_modules(${target} ${OPENCV_MODULE_${d}_DEPS})
599 600
      endif()
    elseif(EXISTS "${d}")
Alexander Alekhin's avatar
Alexander Alekhin committed
601
      ocv_target_include_directories(${target} "${d}")
602 603 604 605
    endif()
  endforeach()
endmacro()

606 607 608
# setup include path for OpenCV headers for specified module
# ocv_module_include_directories(<extra include directories/extra include modules>)
macro(ocv_module_include_directories)
Alexander Alekhin's avatar
Alexander Alekhin committed
609 610 611 612 613 614
  ocv_target_include_directories(${the_module}
      "${OPENCV_MODULE_${the_module}_LOCATION}/include"
      "${OPENCV_MODULE_${the_module}_LOCATION}/src"
      "${CMAKE_CURRENT_BINARY_DIR}" # for precompiled headers
      )
  ocv_target_include_modules(${the_module} ${OPENCV_MODULE_${the_module}_DEPS} ${ARGN})
615
endmacro()
616 617


618 619 620 621 622
# sets header and source files for the current module
# NB: all files specified as headers will be installed
# Usage:
# ocv_set_module_sources([HEADERS] <list of files> [SOURCES] <list of files>)
macro(ocv_set_module_sources)
Alexander Alekhin's avatar
Alexander Alekhin committed
623 624
  ocv_debug_message("ocv_set_module_sources(" ${ARGN} ")")

625 626
  set(OPENCV_MODULE_${the_module}_HEADERS "")
  set(OPENCV_MODULE_${the_module}_SOURCES "")
627

628 629 630 631 632 633 634
  foreach(f "HEADERS" ${ARGN})
    if(f STREQUAL "HEADERS" OR f STREQUAL "SOURCES")
      set(__filesvar "OPENCV_MODULE_${the_module}_${f}")
    else()
      list(APPEND ${__filesvar} "${f}")
    endif()
  endforeach()
635

636 637 638 639
  # the hacky way to embeed any files into the OpenCV without modification of its build system
  if(COMMAND ocv_get_module_external_sources)
    ocv_get_module_external_sources()
  endif()
640

641
  # use full paths for module to be independent from the module location
642
  ocv_convert_to_full_paths(OPENCV_MODULE_${the_module}_HEADERS)
643

644 645 646
  set(OPENCV_MODULE_${the_module}_HEADERS ${OPENCV_MODULE_${the_module}_HEADERS} CACHE INTERNAL "List of header files for ${the_module}")
  set(OPENCV_MODULE_${the_module}_SOURCES ${OPENCV_MODULE_${the_module}_SOURCES} CACHE INTERNAL "List of source files for ${the_module}")
endmacro()
647

648 649
# finds and sets headers and sources for the standard OpenCV module
# Usage:
650
# ocv_glob_module_sources([EXCLUDE_CUDA] <extra sources&headers in the same format as used in ocv_set_module_sources>)
651
macro(ocv_glob_module_sources)
Alexander Alekhin's avatar
Alexander Alekhin committed
652
  ocv_debug_message("ocv_glob_module_sources(" ${ARGN} ")")
653 654 655 656 657 658
  set(_argn ${ARGN})
  list(FIND _argn "EXCLUDE_CUDA" exclude_cuda)
  if(NOT exclude_cuda EQUAL -1)
    list(REMOVE_AT _argn ${exclude_cuda})
  endif()

Alexander Alekhin's avatar
Alexander Alekhin committed
659 660 661 662 663 664 665 666 667 668 669
  file(GLOB_RECURSE lib_srcs
       "${CMAKE_CURRENT_LIST_DIR}/src/*.cpp"
  )
  file(GLOB_RECURSE lib_int_hdrs
       "${CMAKE_CURRENT_LIST_DIR}/src/*.hpp"
       "${CMAKE_CURRENT_LIST_DIR}/src/*.h"
  )
  file(GLOB lib_hdrs
       "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/*.hpp"
       "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/*.hpp"
       "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/*.h"
670 671
       "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/hal/*.hpp"
       "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/hal/*.h"
Alexander Alekhin's avatar
Alexander Alekhin committed
672 673 674 675 676
  )
  file(GLOB lib_hdrs_detail
       "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/detail/*.hpp"
       "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/detail/*.h"
  )
677
  if (APPLE)
Alexander Alekhin's avatar
Alexander Alekhin committed
678 679 680
    file(GLOB_RECURSE lib_srcs_apple
         "${CMAKE_CURRENT_LIST_DIR}/src/*.mm"
    )
681 682
    list(APPEND lib_srcs ${lib_srcs_apple})
  endif()
683

Alexander Alekhin's avatar
Alexander Alekhin committed
684 685
  ocv_source_group("Src" DIRBASE "${CMAKE_CURRENT_LIST_DIR}/src" FILES ${lib_srcs} ${lib_int_hdrs})
  ocv_source_group("Include" DIRBASE "${CMAKE_CURRENT_LIST_DIR}/include" FILES ${lib_hdrs} ${lib_hdrs_detail})
686

687 688 689
  set(lib_cuda_srcs "")
  set(lib_cuda_hdrs "")
  if(HAVE_CUDA AND exclude_cuda EQUAL -1)
Alexander Alekhin's avatar
Alexander Alekhin committed
690 691 692
    file(GLOB lib_cuda_srcs
         "${CMAKE_CURRENT_LIST_DIR}/src/cuda/*.cu"
    )
693 694 695 696
    file(GLOB lib_cuda_hdrs
         "${CMAKE_CURRENT_LIST_DIR}/src/cuda/*.hpp"
    )
    source_group("Src\\Cuda"      FILES ${lib_cuda_srcs} ${lib_cuda_hdrs})
697 698
  endif()

Alexander Alekhin's avatar
Alexander Alekhin committed
699 700 701
  file(GLOB cl_kernels
       "${CMAKE_CURRENT_LIST_DIR}/src/opencl/*.cl"
  )
702
  if(cl_kernels)
Alexander Alekhin's avatar
Alexander Alekhin committed
703
    set(OCL_NAME opencl_kernels_${name})
704
    add_custom_command(
Alexander Alekhin's avatar
Alexander Alekhin committed
705
      OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp"
706
      COMMAND ${CMAKE_COMMAND} "-DMODULE_NAME=${name}" "-DCL_DIR=${CMAKE_CURRENT_LIST_DIR}/src/opencl" "-DOUTPUT=${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" -P "${OpenCV_SOURCE_DIR}/cmake/cl2cpp.cmake"
707
      DEPENDS ${cl_kernels} "${OpenCV_SOURCE_DIR}/cmake/cl2cpp.cmake")
708
    ocv_source_group("Src\\opencl\\kernels" FILES ${cl_kernels})
Alexander Alekhin's avatar
Alexander Alekhin committed
709 710
    ocv_source_group("Src\\opencl\\kernels\\autogenerated" FILES "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp")
    list(APPEND lib_srcs ${cl_kernels} "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp")
711 712
  endif()

713
  ocv_set_module_sources(${_argn} HEADERS ${lib_hdrs} ${lib_hdrs_detail}
714
                         SOURCES ${lib_srcs} ${lib_int_hdrs} ${lib_cuda_srcs} ${lib_cuda_hdrs})
715 716
endmacro()

717 718 719
# creates OpenCV module in current folder
# creates new target, configures standard dependencies, compilers flags, install rules
# Usage:
720
#   ocv_create_module(<extra link dependencies>)
Alexander Alekhin's avatar
Alexander Alekhin committed
721
#   ocv_create_module()
722
macro(ocv_create_module)
Alexander Alekhin's avatar
Alexander Alekhin committed
723 724 725 726 727 728 729 730 731
  ocv_debug_message("ocv_create_module(" ${ARGN} ")")
  set(OPENCV_MODULE_${the_module}_LINK_DEPS "${OPENCV_MODULE_${the_module}_LINK_DEPS};${ARGN}" CACHE INTERNAL "")
  if(${BUILD_opencv_world} AND OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD)
    # nothing
    set(the_module_target opencv_world)
  else()
    _ocv_create_module(${ARGN})
    set(the_module_target ${the_module})
  endif()
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753

  if(WINRT)
    # removing APPCONTAINER from modules to run from console
    # in case of usual starting of WinRT test apps output is missing
    # so starting of console version w/o APPCONTAINER is required to get test results
    # also this allows to use opencv_extra test data for these tests
    if(NOT "${the_module}" STREQUAL "opencv_ts" AND NOT "${the_module}" STREQUAL "opencv_hal")
      add_custom_command(TARGET ${the_module}
                         POST_BUILD
                         COMMAND link.exe /edit /APPCONTAINER:NO $(TargetPath))
    endif()

    if("${the_module}" STREQUAL "opencv_ts")
      # copy required dll files; WinRT apps need these dlls that are usually substituted by Visual Studio
      # however they are not on path and need to be placed with executables to run from console w/o APPCONTAINER
      add_custom_command(TARGET ${the_module}
        POST_BUILD
        COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\msvcp$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\msvcp$(PlatformToolsetVersion)_app.dll\""
        COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\msvcr$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\msvcr$(PlatformToolsetVersion)_app.dll\""
        COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\vccorlib$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\vccorlib$(PlatformToolsetVersion)_app.dll\"")
    endif()
  endif()
Alexander Alekhin's avatar
Alexander Alekhin committed
754 755 756
endmacro()

macro(_ocv_create_module)
757 758 759
  # The condition we ought to be testing here is whether ocv_add_precompiled_headers will
  # be called at some point in the future. We can't look into the future, though,
  # so this will have to do.
Alexander Alekhin's avatar
Alexander Alekhin committed
760
  if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/precomp.hpp" AND NOT ${the_module} STREQUAL opencv_world)
761 762 763
    get_native_precompiled_header(${the_module} precomp.hpp)
  endif()

764 765 766
  set(sub_objs "")
  set(sub_links "")
  set(cuda_objs "")
Maksim Shabunin's avatar
Maksim Shabunin committed
767
  if (OPENCV_MODULE_${the_module}_CHILDREN)
768
    message(STATUS "Complex module ${the_module}")
769
    foreach (m ${OPENCV_MODULE_${the_module}_CHILDREN})
770
      if (BUILD_${m} AND TARGET ${m}_object)
771 772 773
        get_target_property(_sub_links ${m} LINK_LIBRARIES)
        list(APPEND sub_objs $<TARGET_OBJECTS:${m}_object>)
        list(APPEND sub_links ${_sub_links})
774
        message(STATUS "    + ${m}")
775
      else()
776
        message(STATUS "    - ${m}")
777 778 779 780 781
      endif()
      list(APPEND cuda_objs ${OPENCV_MODULE_${m}_CUDA_OBJECTS})
    endforeach()
  endif()

782 783
  source_group("Include" FILES "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp")
  source_group("Src" FILES "${${the_module}_pch}")
Alexander Alekhin's avatar
Alexander Alekhin committed
784
  ocv_add_library(${the_module} ${OPENCV_MODULE_TYPE} ${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES}
785
    "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp"
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    ${${the_module}_pch} ${sub_objs})

  if (cuda_objs)
    target_link_libraries(${the_module} ${cuda_objs})
  endif()

  # TODO: is it needed?
  if (sub_links)
    ocv_list_filterout(sub_links "^opencv_")
    ocv_list_unique(sub_links)
    target_link_libraries(${the_module} ${sub_links})
  endif()

  unset(sub_objs)
  unset(sub_links)
  unset(cuda_objs)

803 804 805 806
  set_target_properties(${the_module} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Module")
  set_source_files_properties(${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES} ${${the_module}_pch}
    PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Module")

807 808 809 810 811 812 813 814 815 816 817 818 819 820
  if(NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB)
    ocv_target_link_libraries(${the_module} ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
    ocv_target_link_libraries(${the_module} LINK_INTERFACE_LIBRARIES ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
    ocv_target_link_libraries(${the_module} ${OPENCV_MODULE_${the_module}_DEPS_EXT} ${OPENCV_LINKER_LIBS} ${IPP_LIBS} ${ARGN})
    if (HAVE_CUDA)
      ocv_target_link_libraries(${the_module} ${CUDA_LIBRARIES} ${CUDA_npp_LIBRARY})
    endif()
  else()
    ocv_target_link_libraries(${the_module} LINK_PRIVATE ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
    ocv_target_link_libraries(${the_module} LINK_PRIVATE ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
    ocv_target_link_libraries(${the_module} LINK_PRIVATE ${OPENCV_MODULE_${the_module}_DEPS_EXT} ${OPENCV_LINKER_LIBS} ${IPP_LIBS} ${ARGN})
    if (HAVE_CUDA)
      ocv_target_link_libraries(${the_module} LINK_PRIVATE ${CUDA_LIBRARIES} ${CUDA_npp_LIBRARY})
    endif()
821
  endif()
822

823
  add_dependencies(opencv_modules ${the_module})
824

825 826 827
  if(ENABLE_SOLUTION_FOLDERS)
    set_target_properties(${the_module} PROPERTIES FOLDER "modules")
  endif()
828

829 830 831
  set_target_properties(${the_module} PROPERTIES
    OUTPUT_NAME "${the_module}${OPENCV_DLLVERSION}"
    DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
832 833
    COMPILE_PDB_NAME "${the_module}${OPENCV_DLLVERSION}"
    COMPILE_PDB_NAME_DEBUG "${the_module}${OPENCV_DLLVERSION}${OPENCV_DEBUG_POSTFIX}"
834
    ARCHIVE_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
835
    COMPILE_PDB_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
836
    LIBRARY_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
837 838
    RUNTIME_OUTPUT_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}
  )
839

840 841 842 843 844
  # For dynamic link numbering convenions
  if(NOT ANDROID)
    # Android SDK build scripts can include only .so files into final .apk
    # As result we should not set version properties for Android
    set_target_properties(${the_module} PROPERTIES
845
      VERSION ${OPENCV_LIBVERSION}
846 847 848 849
      SOVERSION ${OPENCV_SOVERSION}
    )
  endif()

850 851
  if((NOT DEFINED OPENCV_MODULE_TYPE AND BUILD_SHARED_LIBS)
      OR (DEFINED OPENCV_MODULE_TYPE AND OPENCV_MODULE_TYPE STREQUAL SHARED))
852
    set_target_properties(${the_module} PROPERTIES COMPILE_DEFINITIONS CVAPI_EXPORTS)
853
    set_target_properties(${the_module} PROPERTIES DEFINE_SYMBOL CVAPI_EXPORTS)
854
  endif()
Andrey Kamaev's avatar
Andrey Kamaev committed
855

856 857 858
  if(MSVC)
    if(CMAKE_CROSSCOMPILING)
      set_target_properties(${the_module} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:secchk")
859
    endif()
860
    set_target_properties(${the_module} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:libc /DEBUG")
861
  endif()
862

863
  get_target_property(_target_type ${the_module} TYPE)
864 865
  if(OPENCV_MODULE_${the_module}_CLASS STREQUAL "PUBLIC" AND
      ("${_target_type}" STREQUAL "SHARED_LIBRARY" OR (NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB)))
866 867 868 869 870 871
    ocv_install_target(${the_module} EXPORT OpenCVModules OPTIONAL
      RUNTIME DESTINATION ${OPENCV_BIN_INSTALL_PATH} COMPONENT libs
      LIBRARY DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT libs NAMELINK_SKIP
      ARCHIVE DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT dev
      )
  endif()
872 873 874 875
  if("${_target_type}" STREQUAL "SHARED_LIBRARY")
    install(TARGETS ${the_module}
      LIBRARY DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT dev NAMELINK_ONLY)
  endif()
876

877 878 879 880 881 882 883 884 885 886 887 888
  foreach(m ${OPENCV_MODULE_${the_module}_CHILDREN} ${the_module})
    # only "public" headers need to be installed
    if(OPENCV_MODULE_${m}_HEADERS AND ";${OPENCV_MODULES_PUBLIC};" MATCHES ";${m};")
      foreach(hdr ${OPENCV_MODULE_${m}_HEADERS})
        string(REGEX REPLACE "^.*opencv2/" "opencv2/" hdr2 "${hdr}")
        if(NOT hdr2 MATCHES "opencv2/${m}/private.*" AND hdr2 MATCHES "^(opencv2/?.*)/[^/]+.h(..)?$" )
          install(FILES ${hdr} OPTIONAL DESTINATION "${OPENCV_INCLUDE_INSTALL_PATH}/${CMAKE_MATCH_1}" COMPONENT dev)
        endif()
      endforeach()
    endif()
  endforeach()

Alexander Alekhin's avatar
Alexander Alekhin committed
889
  _ocv_add_precompiled_headers(${the_module})
890 891 892 893

  if (TARGET ${the_module}_object)
    # copy COMPILE_DEFINITIONS
    get_target_property(main_defs ${the_module} COMPILE_DEFINITIONS)
Maksim Shabunin's avatar
Maksim Shabunin committed
894 895 896
    if (main_defs)
      set_target_properties(${the_module}_object PROPERTIES COMPILE_DEFINITIONS ${main_defs})
    endif()
897 898 899 900 901
    # use same PCH
    if (TARGET pch_Generate_${the_module})
      add_dependencies(${the_module}_object pch_Generate_${the_module} )
    endif()
  endif()
902 903 904 905 906 907
endmacro()

# opencv precompiled headers macro (can add pch to modules and tests)
# this macro must be called after any "add_definitions" commands, otherwise precompiled headers will not work
# Usage:
# ocv_add_precompiled_headers(${the_module})
Alexander Alekhin's avatar
Alexander Alekhin committed
908 909 910
macro(_ocv_add_precompiled_headers the_target)
  ocv_debug_message("ocv_add_precompiled_headers(" ${the_target} ${ARGN} ")")

911 912 913 914 915 916 917 918 919
  if("${the_target}" MATCHES "^opencv_test_.*$")
    SET(pch_path "test/test_")
  elseif("${the_target}" MATCHES "^opencv_perf_.*$")
    SET(pch_path "perf/perf_")
  else()
    SET(pch_path "src/")
  endif()
  ocv_add_precompiled_header_to_target(${the_target} "${CMAKE_CURRENT_SOURCE_DIR}/${pch_path}precomp.hpp")
  unset(pch_path)
920
endmacro()
921

922 923 924
# short command for adding simple OpenCV module
# see ocv_add_module for argument details
# Usage:
925
# ocv_define_module(module_name  [INTERNAL] [EXCLUDE_CUDA] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>] [WRAP <list of wrappers>])
926
macro(ocv_define_module module_name)
Alexander Alekhin's avatar
Alexander Alekhin committed
927
  ocv_debug_message("ocv_define_module(" ${module_name} ${ARGN} ")")
928 929 930 931 932 933
  set(_argn ${ARGN})
  set(exclude_cuda "")
  foreach(arg ${_argn})
    if("${arg}" STREQUAL "EXCLUDE_CUDA")
      set(exclude_cuda "${arg}")
      list(REMOVE_ITEM _argn ${arg})
934 935 936
    endif()
  endforeach()

937 938
  ocv_add_module(${module_name} ${_argn})
  ocv_glob_module_sources(${exclude_cuda})
Alexander Alekhin's avatar
Alexander Alekhin committed
939
  ocv_module_include_directories()
940 941 942 943
  ocv_create_module()

  ocv_add_accuracy_tests()
  ocv_add_perf_tests()
944
  ocv_add_samples()
945
endmacro()
946

947 948 949 950 951 952 953 954
# ensures that all passed modules are available
# sets OCV_DEPENDENCIES_FOUND variable to TRUE/FALSE
macro(ocv_check_dependencies)
  set(OCV_DEPENDENCIES_FOUND TRUE)
  foreach(d ${ARGN})
    if(d MATCHES "^opencv_[^ ]+$" AND NOT HAVE_${d})
      set(OCV_DEPENDENCIES_FOUND FALSE)
      break()
955
    endif()
956
  endforeach()
957 958
endmacro()

959
# auxiliary macro to parse arguments of ocv_add_accuracy_tests and ocv_add_perf_tests commands
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
macro(__ocv_parse_test_sources tests_type)
  set(OPENCV_${tests_type}_${the_module}_SOURCES "")
  set(OPENCV_${tests_type}_${the_module}_DEPS "")
  set(__file_group_name "")
  set(__file_group_sources "")
  foreach(arg "DEPENDS_ON" ${ARGN} "FILES")
    if(arg STREQUAL "FILES")
      set(__currentvar "__file_group_sources")
      if(__file_group_name AND __file_group_sources)
        source_group("${__file_group_name}" FILES ${__file_group_sources})
        list(APPEND OPENCV_${tests_type}_${the_module}_SOURCES ${__file_group_sources})
      endif()
      set(__file_group_name "")
      set(__file_group_sources "")
    elseif(arg STREQUAL "DEPENDS_ON")
Alexander Alekhin's avatar
Alexander Alekhin committed
975
      set(__currentvar "OPENCV_${tests_type}_${the_module}_DEPS")
976
    elseif(" ${__currentvar}" STREQUAL " __file_group_sources" AND NOT __file_group_name) # spaces to avoid CMP0054
977 978 979 980 981 982 983 984 985
      set(__file_group_name "${arg}")
    else()
      list(APPEND ${__currentvar} "${arg}")
    endif()
  endforeach()
  unset(__file_group_name)
  unset(__file_group_sources)
  unset(__currentvar)
endmacro()
986

987 988
# this is a command for adding OpenCV performance tests to the module
# ocv_add_perf_tests(<extra_dependencies>)
989
function(ocv_add_perf_tests)
Alexander Alekhin's avatar
Alexander Alekhin committed
990 991
  ocv_debug_message("ocv_add_perf_tests(" ${ARGN} ")")

992 993 994 995
  if(WINRT)
    set(OPENCV_DEBUG_POSTFIX "")
  endif()

Alexander Alekhin's avatar
Alexander Alekhin committed
996
  set(perf_path "${CMAKE_CURRENT_LIST_DIR}/perf")
997 998
  if(BUILD_PERF_TESTS AND EXISTS "${perf_path}")
    __ocv_parse_test_sources(PERF ${ARGN})
999

1000
    # opencv_imgcodecs is required for imread/imwrite
1001
    set(perf_deps opencv_ts ${the_module} opencv_imgcodecs ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_opencv_ts_DEPS})
1002
    ocv_check_dependencies(${perf_deps})
1003

1004 1005
    if(OCV_DEPENDENCIES_FOUND)
      set(the_target "opencv_perf_${name}")
1006
      # project(${the_target})
1007

1008
      if(NOT OPENCV_PERF_${the_module}_SOURCES)
1009 1010
        file(GLOB_RECURSE perf_srcs "${perf_path}/*.cpp")
        file(GLOB_RECURSE perf_hdrs "${perf_path}/*.hpp" "${perf_path}/*.h")
1011 1012
        ocv_source_group("Src" DIRBASE "${perf_path}" FILES ${perf_srcs})
        ocv_source_group("Include" DIRBASE "${perf_path}" FILES ${perf_hdrs})
1013 1014
        set(OPENCV_PERF_${the_module}_SOURCES ${perf_srcs} ${perf_hdrs})
      endif()
1015

Alexander Alekhin's avatar
Alexander Alekhin committed
1016 1017 1018
      if(NOT BUILD_opencv_world)
        get_native_precompiled_header(${the_target} perf_precomp.hpp)
      endif()
1019

1020
      source_group("Src" FILES "${${the_target}_pch}")
Alexander Alekhin's avatar
Alexander Alekhin committed
1021 1022
      ocv_add_executable(${the_target} ${OPENCV_PERF_${the_module}_SOURCES} ${${the_target}_pch})
      ocv_target_include_modules(${the_target} ${perf_deps} "${perf_path}")
1023
      ocv_target_link_libraries(${the_target} ${perf_deps} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_LINKER_LIBS})
1024
      add_dependencies(opencv_perf_tests ${the_target})
1025

1026 1027 1028 1029
      set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};PerfTest")
      set_source_files_properties(${OPENCV_PERF_${the_module}_SOURCES} ${${the_target}_pch}
        PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};PerfTest")

1030 1031 1032 1033 1034 1035 1036 1037 1038
      # Additional target properties
      set_target_properties(${the_target} PROPERTIES
        DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
        RUNTIME_OUTPUT_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}"
      )
      if(ENABLE_SOLUTION_FOLDERS)
        set_target_properties(${the_target} PROPERTIES FOLDER "tests performance")
      endif()

1039 1040 1041 1042 1043 1044 1045 1046
      if(WINRT)
        # removing APPCONTAINER from tests to run from console
        # look for detailed description inside of ocv_create_module macro above
        add_custom_command(TARGET "opencv_perf_${name}"
                           POST_BUILD
                           COMMAND link.exe /edit /APPCONTAINER:NO $(TargetPath))
      endif()

Alexander Alekhin's avatar
Alexander Alekhin committed
1047 1048 1049
      if(NOT BUILD_opencv_world)
        _ocv_add_precompiled_headers(${the_target})
      endif()
1050 1051 1052 1053 1054 1055

      ocv_add_test_from_target("${the_target}" "Performance" "${the_target}")
      ocv_add_test_from_target("opencv_sanity_${name}" "Sanity" "${the_target}"
                               "--perf_min_samples=1"
                               "--perf_force_samples=1"
                               "--perf_verify_sanity")
1056
    else(OCV_DEPENDENCIES_FOUND)
1057
      # TODO: warn about unsatisfied dependencies
1058
    endif(OCV_DEPENDENCIES_FOUND)
1059
    if(INSTALL_TESTS)
1060
      install(TARGETS ${the_target} RUNTIME DESTINATION ${OPENCV_TEST_INSTALL_PATH} COMPONENT tests)
1061
    endif()
1062
  endif()
1063
endfunction()
1064

1065 1066
# this is a command for adding OpenCV accuracy/regression tests to the module
# ocv_add_accuracy_tests([FILES <source group name> <list of sources>] [DEPENDS_ON] <list of extra dependencies>)
1067
function(ocv_add_accuracy_tests)
Alexander Alekhin's avatar
Alexander Alekhin committed
1068 1069
  ocv_debug_message("ocv_add_accuracy_tests(" ${ARGN} ")")

1070 1071 1072 1073
  if(WINRT)
    set(OPENCV_DEBUG_POSTFIX "")
  endif()

Alexander Alekhin's avatar
Alexander Alekhin committed
1074
  set(test_path "${CMAKE_CURRENT_LIST_DIR}/test")
1075 1076 1077
  if(BUILD_TESTS AND EXISTS "${test_path}")
    __ocv_parse_test_sources(TEST ${ARGN})

1078
    # opencv_imgcodecs is required for imread/imwrite
1079
    set(test_deps opencv_ts ${the_module} opencv_imgcodecs opencv_videoio ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_opencv_ts_DEPS})
1080 1081 1082
    ocv_check_dependencies(${test_deps})
    if(OCV_DEPENDENCIES_FOUND)
      set(the_target "opencv_test_${name}")
1083
      # project(${the_target})
1084

1085
      if(NOT OPENCV_TEST_${the_module}_SOURCES)
1086 1087
        file(GLOB_RECURSE test_srcs "${test_path}/*.cpp")
        file(GLOB_RECURSE test_hdrs "${test_path}/*.hpp" "${test_path}/*.h")
1088 1089
        ocv_source_group("Src" DIRBASE "${test_path}" FILES ${test_srcs})
        ocv_source_group("Include" DIRBASE "${test_path}" FILES ${test_hdrs})
1090 1091
        set(OPENCV_TEST_${the_module}_SOURCES ${test_srcs} ${test_hdrs})
      endif()
1092

Alexander Alekhin's avatar
Alexander Alekhin committed
1093 1094 1095
      if(NOT BUILD_opencv_world)
        get_native_precompiled_header(${the_target} test_precomp.hpp)
      endif()
1096

1097
      source_group("Src" FILES "${${the_target}_pch}")
Alexander Alekhin's avatar
Alexander Alekhin committed
1098 1099
      ocv_add_executable(${the_target} ${OPENCV_TEST_${the_module}_SOURCES} ${${the_target}_pch})
      ocv_target_include_modules(${the_target} ${test_deps} "${test_path}")
1100
      ocv_target_link_libraries(${the_target} ${test_deps} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_LINKER_LIBS})
1101
      add_dependencies(opencv_tests ${the_target})
1102

1103 1104 1105 1106
      set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};AccuracyTest")
      set_source_files_properties(${OPENCV_TEST_${the_module}_SOURCES} ${${the_target}_pch}
        PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};AccuracyTest")

1107 1108 1109 1110 1111 1112 1113 1114 1115
      # Additional target properties
      set_target_properties(${the_target} PROPERTIES
        DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
        RUNTIME_OUTPUT_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}"
      )

      if(ENABLE_SOLUTION_FOLDERS)
        set_target_properties(${the_target} PROPERTIES FOLDER "tests accuracy")
      endif()
1116

1117 1118 1119 1120
      if(OPENCV_TEST_BIGDATA)
        ocv_append_target_property(${the_target} COMPILE_DEFINITIONS "OPENCV_TEST_BIGDATA=1")
      endif()

Alexander Alekhin's avatar
Alexander Alekhin committed
1121 1122 1123
      if(NOT BUILD_opencv_world)
        _ocv_add_precompiled_headers(${the_target})
      endif()
1124 1125

      ocv_add_test_from_target("${the_target}" "Accuracy" "${the_target}")
1126
    else(OCV_DEPENDENCIES_FOUND)
1127
      # TODO: warn about unsatisfied dependencies
1128
    endif(OCV_DEPENDENCIES_FOUND)
1129 1130

    if(INSTALL_TESTS)
1131
      install(TARGETS ${the_target} RUNTIME DESTINATION ${OPENCV_TEST_INSTALL_PATH} COMPONENT tests)
1132
    endif()
1133
  endif()
1134
endfunction()
1135

1136
function(ocv_add_samples)
Alexander Alekhin's avatar
Alexander Alekhin committed
1137 1138
  ocv_debug_message("ocv_add_samples(" ${ARGN} ")")

1139 1140 1141 1142
  set(samples_path "${CMAKE_CURRENT_SOURCE_DIR}/samples")
  string(REGEX REPLACE "^opencv_" "" module_id ${the_module})

  if(BUILD_EXAMPLES AND EXISTS "${samples_path}")
1143
    set(samples_deps ${the_module} ${OPENCV_MODULE_${the_module}_DEPS} opencv_imgcodecs opencv_videoio opencv_highgui ${ARGN})
1144 1145 1146 1147 1148 1149 1150 1151 1152
    ocv_check_dependencies(${samples_deps})

    if(OCV_DEPENDENCIES_FOUND)
      file(GLOB sample_sources "${samples_path}/*.cpp")

      foreach(source ${sample_sources})
        get_filename_component(name "${source}" NAME_WE)
        set(the_target "example_${module_id}_${name}")

Alexander Alekhin's avatar
Alexander Alekhin committed
1153 1154 1155
        ocv_add_executable(${the_target} "${source}")
        ocv_target_include_modules(${the_target} ${samples_deps})
        ocv_target_link_libraries(${the_target} ${samples_deps})
1156 1157
        set_target_properties(${the_target} PROPERTIES PROJECT_LABEL "(sample) ${name}")

1158 1159 1160 1161
        set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Sample")
        set_source_files_properties("${source}"
          PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Sample")

1162 1163 1164 1165 1166 1167 1168
        if(ENABLE_SOLUTION_FOLDERS)
          set_target_properties(${the_target} PROPERTIES
            OUTPUT_NAME "${module_id}-example-${name}"
            FOLDER "samples/${module_id}")
        endif()

        if(WIN32)
1169
          install(TARGETS ${the_target} RUNTIME DESTINATION "samples/${module_id}" COMPONENT samples)
1170 1171 1172 1173 1174 1175
        endif()
      endforeach()
    endif()
  endif()

  if(INSTALL_C_EXAMPLES AND NOT WIN32 AND EXISTS "${samples_path}")
1176 1177 1178 1179 1180 1181 1182 1183
  file(GLOB DEPLOY_FILES_AND_DIRS "${samples_path}/*")
    foreach(ITEM ${DEPLOY_FILES_AND_DIRS})
        IF( IS_DIRECTORY "${ITEM}" )
            LIST( APPEND sample_dirs "${ITEM}" )
        ELSE()
            LIST( APPEND sample_files "${ITEM}" )
        ENDIF()
    endforeach()
1184
    install(FILES ${sample_files}
1185
            DESTINATION ${OPENCV_SAMPLES_SRC_INSTALL_PATH}/${module_id}
1186
            PERMISSIONS OWNER_READ GROUP_READ WORLD_READ COMPONENT samples)
1187 1188 1189
    install(DIRECTORY ${sample_dirs}
            DESTINATION ${OPENCV_SAMPLES_SRC_INSTALL_PATH}/${module_id}
            USE_SOURCE_PERMISSIONS COMPONENT samples)
1190 1191
  endif()
endfunction()