diff --git a/CHANGELOG.md b/CHANGELOG.md index d2618baec..9f807dd8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Change Log +## [5.6.0] +- Introduced Dynamic Workflows + +## [5.5.0] +- Updated to Opencast API 1.5.0 +- Introduced Publication Usages and solved issue #182 + +## [5.4.1] +- Fixed a compatibility issue in the new caching service. + +## [5.4.0] +- Implemented improved Caching Service which fixes #194 + +## [5.3.2] +- Fix #220: Upload of large files lead to a memory limit error. +- Fixed the Overlay when creating a new Event. + +## [5.3.1] +- Fix #11 and #113: Introducing new Paella 7 Player + ## [5.3.0] - Implemented #193: The Chunk Size for Uploads is now configurable. The default value is 20MB, this can be changes in the plugin configuration. - Fix #176: Fixed a static timeout in fileuploads, this now uses max_execution_time of the server. diff --git a/classes/Conf/PermissionTemplates/class.xoctPermissionTemplateTableGUI.php b/classes/Conf/PermissionTemplates/class.xoctPermissionTemplateTableGUI.php index 9a207280b..dc7762a8d 100644 --- a/classes/Conf/PermissionTemplates/class.xoctPermissionTemplateTableGUI.php +++ b/classes/Conf/PermissionTemplates/class.xoctPermissionTemplateTableGUI.php @@ -57,7 +57,8 @@ public function __construct(xoctPermissionTemplateGUI $a_parent_obj, $a_parent_c $b->setUrl($this->ctrl->getLinkTarget($a_parent_obj, xoctPermissionTemplateGUI::CMD_ADD)); $this->addCommandButtonInstance($b); - xoctWaiterGUI::initJS(); + new WaitOverlay($this->main_tpl); // TODO check if needed + $this->main_tpl->addJavaScript($this->plugin->getDirectory() . '/templates/default/sortable.js'); $base_link = $this->ctrl->getLinkTarget($this->parent_obj, 'reorder', '', true); $this->main_tpl->addOnLoadCode("xoctSortable.init('" . $base_link . "');"); diff --git a/classes/Conf/PublicationUsage/class.xoctPublicationGroupFormGUI.php b/classes/Conf/PublicationUsage/class.xoctPublicationGroupFormGUI.php new file mode 100644 index 000000000..11e02f61a --- /dev/null +++ b/classes/Conf/PublicationUsage/class.xoctPublicationGroupFormGUI.php @@ -0,0 +1,154 @@ + + */ +class xoctPublicationGroupFormGUI extends ilPropertyFormGUI +{ + public const F_NAME = 'name'; + public const F_DISPLAY_NAME = 'display_name'; + public const F_DESCRIPTION = 'description'; + public const F_DISPLAY_NAME_MAX_LENGTH = 10; + + /** + * @var PublicationUsageGroup + */ + protected $object; + /** + * @var xoctPublicationUsageGUI + */ + protected $parent_gui; + /** + * @var bool $is_new + */ + protected $is_new = true; + + + + /** + * @param xoctPublicationUsageGUI $parent_gui + * @param PublicationUsageGroup $xoctPublicationUsageGroup + * @param bool $is_new + */ + public function __construct($parent_gui, $xoctPublicationUsageGroup, $is_new = true) + { + parent::__construct(); + $this->object = $xoctPublicationUsageGroup; + $this->parent_gui = $parent_gui; + $this->parent_gui->setTab(); + $this->ctrl->saveParameter($parent_gui, 'id'); + $this->is_new = $is_new; + $this->initForm(); + } + + + /** + * + */ + protected function initForm() + { + $this->setTarget('_top'); + $this->setFormAction($this->ctrl->getFormAction($this->parent_gui)); + $this->initButtons(); + + $te = new ilTextInputGUI($this->txt(self::F_NAME), self::F_NAME); + $te->setRequired(true); + $this->addItem($te); + + $max_lenght = self::F_DISPLAY_NAME_MAX_LENGTH; + $display_name = (!empty($this->object->getDisplayName()) ? $this->object->getDisplayName() : '{added display name}'); + $info = sprintf($this->txt(self::F_DISPLAY_NAME . '_info'), $max_lenght, strtolower($display_name)); + $te = new ilTextInputGUI($this->txt(self::F_DISPLAY_NAME), self::F_DISPLAY_NAME); + $te->setInfo($info); + $te->setMaxLength($max_lenght); + $te->setRequired(true); + $this->addItem($te); + + $te = new ilTextAreaInputGUI($this->txt(self::F_DESCRIPTION), self::F_DESCRIPTION); + $this->addItem($te); + } + + + /** + * @param $lang_var + * + * @return string + */ + protected function txt($lang_var): string + { + return $this->parent_gui->txt("group_{$lang_var}"); + } + + + /** + * + */ + public function fillForm() + { + $array = [ + self::F_NAME => $this->object->getName(), + self::F_DISPLAY_NAME => $this->object->getDisplayName(), + self::F_DESCRIPTION => $this->object->getDescription(), + ]; + + $this->setValuesByArray($array); + } + + + /** + * returns whether checkinput was successful or not. + * + * @return bool + */ + public function fillObject(): bool + { + if (!$this->checkInput()) { + return false; + } + + $this->object->setName($this->getInput(self::F_NAME)); + $this->object->setDisplayName($this->getInput(self::F_DISPLAY_NAME)); + $this->object->setDescription($this->getInput(self::F_DESCRIPTION)); + + return true; + } + + + /** + * @return bool + */ + public function saveObject(): bool + { + if (!$this->fillObject()) { + return false; + } + if ($this->is_new) { + $this->object->create(); + } else { + $this->object->update(); + } + + return true; + } + + + /** + * + */ + protected function initButtons() + { + if ($this->is_new) { + $this->setTitle($this->parent_gui->txt('create_group')); + $this->addCommandButton(xoctPublicationUsageGUI::CMD_CREATE_NEW_GROUP, $this->parent_gui->txt(xoctPublicationUsageGUI::CMD_CREATE)); + } else { + $this->setTitle($this->parent_gui->txt('edit_group')); + $this->addCommandButton(xoctPublicationUsageGUI::CMD_UPDATE_GROUP, $this->parent_gui->txt(xoctPublicationUsageGUI::CMD_UPDATE)); + } + + $this->addCommandButton(xoctPublicationUsageGUI::CMD_CANCEL, $this->parent_gui->txt(xoctPublicationUsageGUI::CMD_CANCEL)); + } +} diff --git a/classes/Conf/PublicationUsage/class.xoctPublicationGroupTableGUI.php b/classes/Conf/PublicationUsage/class.xoctPublicationGroupTableGUI.php new file mode 100644 index 000000000..386549ea7 --- /dev/null +++ b/classes/Conf/PublicationUsage/class.xoctPublicationGroupTableGUI.php @@ -0,0 +1,132 @@ + + */ +class xoctPublicationGroupTableGUI extends ilTable2GUI +{ + public const TBL_ID = 'tbl_xoct_pub_g'; + /** + * @var array + */ + protected $filter = []; + /** + * @var ilOpenCastPlugin + */ + protected $plugin; + /** + * @var OpencastDIC + */ + protected $container; + + + /** + * @param xoctPublicationUsageGUI $a_parent_obj + * @param string $a_parent_cmd + */ + public function __construct(xoctPublicationUsageGUI $a_parent_obj, $a_parent_cmd) + { + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->container = OpencastDIC::getInstance(); + $this->plugin = $this->container->plugin(); + $this->setId(self::TBL_ID); + $this->setPrefix(self::TBL_ID); + $this->setFormName(self::TBL_ID); + $this->ctrl->saveParameter($a_parent_obj, $this->getNavParameter()); + $this->parent_obj = $a_parent_obj; + $this->setTitle($this->parent_obj->txt('table_title_usage_group')); + $this->setRowTemplate( + 'tpl.publication_group.html', + 'Customizing/global/plugins/Services/Repository/RepositoryObject/OpenCast' + ); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->initColumns(); + $this->parseData(); + } + + + /** + * @param array $a_set + * + * @throws DICException + */ + public function fillRow($a_set) + { + /** + * @var $publication_usage_group PublicationUsageGroup + */ + $publication_usage_group = PublicationUsageGroup::find($a_set['id']); + $this->tpl->setVariable('NAME', $publication_usage_group->getName()); + $this->tpl->setVariable('DISPLAY_NAME', $publication_usage_group->getDisplayName()); + $this->tpl->setVariable('DESCRIPTION', $publication_usage_group->getDescription()); + + $this->addActionMenu($publication_usage_group); + } + + + protected function initColumns() + { + $this->addColumn($this->parent_obj->txt('group_name')); + $this->addColumn($this->parent_obj->txt('group_display_name')); + $this->addColumn($this->parent_obj->txt('group_description')); + + $this->addColumn($this->plugin->txt('common_actions'), '', '150px'); + } + + + /** + * @param PublicationUsageGroup $publication_usage_group + * + * @throws DICException + */ + protected function addActionMenu(PublicationUsageGroup $publication_usage_group) + { + $current_selection_list = new ilAdvancedSelectionListGUI(); + $current_selection_list->setListTitle($this->plugin->txt('common_actions')); + $current_selection_list->setId(self::TBL_ID . '_actions_' . $publication_usage_group->getId()); + $current_selection_list->setUseImages(false); + + $this->ctrl->setParameter($this->parent_obj, 'id', $publication_usage_group->getId()); + $current_selection_list->addItem( + $this->parent_obj->txt(xoctPublicationUsageGUI::CMD_EDIT), + xoctPublicationUsageGUI::CMD_EDIT_GROUP, + $this->ctrl->getLinkTarget($this->parent_obj, xoctPublicationUsageGUI::CMD_EDIT_GROUP) + ); + $current_selection_list->addItem( + $this->parent_obj->txt(xoctPublicationUsageGUI::CMD_DELETE), + xoctPublicationUsageGUI::CMD_DELETE_GROUP, + $this->ctrl->getLinkTarget($this->parent_obj, xoctPublicationUsageGUI::CMD_CONFIRM_DELETE_GROUP) + ); + + $this->tpl->setVariable('ACTIONS', $current_selection_list->getHTML()); + } + + + protected function parseData() + { + $groups = PublicationUsageGroupRepository::getSortedArrayList(); + $this->setData($groups); + } + + + /** + * @param $item + */ + protected function addAndReadFilterItem(ilFormPropertyGUI $item) + { + $this->addFilterItem($item); + $item->readFromSession(); + if ($item instanceof ilCheckboxInputGUI) { + $this->filter[$item->getPostVar()] = $item->getChecked(); + } else { + $this->filter[$item->getPostVar()] = $item->getValue(); + } + } +} diff --git a/classes/Conf/PublicationUsage/class.xoctPublicationSubUsageFormGUI.php b/classes/Conf/PublicationUsage/class.xoctPublicationSubUsageFormGUI.php new file mode 100644 index 000000000..4baa3b183 --- /dev/null +++ b/classes/Conf/PublicationUsage/class.xoctPublicationSubUsageFormGUI.php @@ -0,0 +1,281 @@ + + */ +class xoctPublicationSubUsageFormGUI extends ilPropertyFormGUI +{ + public const F_PARENT_USAGE_ID = 'parent_usage_id'; + public const F_TITLE = 'title'; + public const F_DESCRIPTION = 'description'; + public const F_DISPLAY_NAME = 'display_name'; + public const F_GROUP_ID = 'group_id'; + public const F_CHANNEL = 'channel'; + public const F_STATUS = 'status'; + public const F_SEARCH_KEY = 'search_key'; + public const F_FLAVOR = PublicationUsage::SEARCH_KEY_FLAVOR; + public const F_TAG = PublicationUsage::SEARCH_KEY_TAG; + public const F_MD_TYPE = 'md_type'; + public const F_ALLOW_MULTIPLE = 'allow_multiple'; + public const F_MEDIATYPE = 'mediatype'; + public const F_IGNORE_OBJECT_SETTINGS = 'ignore_object_settings'; + public const F_EXT_DL_SOURCE = 'ext_dl_source'; + + /** + * @var PublicationUsage + */ + protected $object; + /** + * @var xoctPublicationUsageGUI + */ + protected $parent_gui; + /** + * @var bool $is_new + */ + protected $is_new = true; + /** + * @var ilOpenCastPlugin + */ + protected $plugin; + /** + * @var OpencastDIC + */ + protected $container; + + + /** + * @param xoctPublicationUsageGUI $parent_gui + * @param xoctPublicationSubUsage $xoctPublicationSubUsage + */ + public function __construct($parent_gui, $xoctPublicationSubUsage, $is_new = true) + { + global $DIC; + $this->container = OpencastDIC::getInstance(); + $this->plugin = $this->container->plugin(); + $DIC->ui()->mainTemplate()->addJavaScript( + $this->plugin->getDirectory() . '/js/opencast/dist/index.js' + ); + $DIC->ui()->mainTemplate()->addOnLoadCode('il.Opencast.Form.publicationUsage.init()'); + parent::__construct(); + $this->object = $xoctPublicationSubUsage; + $this->parent_gui = $parent_gui; + $this->parent_gui->setTab(); + $this->ctrl->saveParameter($parent_gui, 'id'); + $this->is_new = $is_new; + $this->initForm(); + } + + + /** + * + */ + protected function initForm() + { + $this->setTarget('_top'); + $this->setFormAction($this->ctrl->getFormAction($this->parent_gui)); + $this->initButtons(); + + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_PARENT_USAGE_ID), self::F_PARENT_USAGE_ID); + $te->setRequired(true); + $te->setDisabled(true); + $this->addItem($te); + + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_TITLE), self::F_TITLE); + $te->setRequired(true); + $te->setDisabled(true); + $this->addItem($te); + + // F_DISPLAY_NAME + $max_lenght = 20; + $display_name = (!empty($this->object->getDisplayName()) ? $this->object->getDisplayName() : '{added display name}'); + $info = sprintf($this->plugin->txt('publication_usage_sub_' . self::F_DISPLAY_NAME . '_info'), $max_lenght, strtolower($display_name)); + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_DISPLAY_NAME), self::F_DISPLAY_NAME); + $te->setInfo($info); + $te->setMaxLength($max_lenght); + $this->addItem($te); + + $te = new ilTextAreaInputGUI($this->parent_gui->txt(self::F_DESCRIPTION), self::F_DESCRIPTION); + $this->addItem($te); + + // F_GROUP_ID + $xoctPublicationUsageGroupsArray = PublicationUsageGroup::getArray('id', 'name'); + $empty_groups = ['' => '-']; + $publication_groups = $empty_groups + $xoctPublicationUsageGroupsArray; + $te = new ilSelectInputGUI($this->parent_gui->txt(self::F_GROUP_ID), self::F_GROUP_ID); + $te->setOptions($publication_groups); + $this->addItem($te); + + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_CHANNEL), self::F_CHANNEL); + $te->setRequired(true); + $this->addItem($te); + + $te = new ilSelectInputGUI($this->parent_gui->txt(self::F_MD_TYPE), self::F_MD_TYPE); + $te->setRequired(true); + $te->setOptions([ + PublicationUsage::MD_TYPE_PUBLICATION_ITSELF => $this->parent_gui->txt( + 'md_type_' . PublicationUsage::MD_TYPE_PUBLICATION_ITSELF + ), + PublicationUsage::MD_TYPE_ATTACHMENT => $this->parent_gui->txt( + 'md_type_' . PublicationUsage::MD_TYPE_ATTACHMENT + ), + PublicationUsage::MD_TYPE_MEDIA => $this->parent_gui->txt('md_type_' . PublicationUsage::MD_TYPE_MEDIA) + ]); + $this->addItem($te); + + $radio = new ilRadioGroupInputGUI($this->parent_gui->txt(self::F_SEARCH_KEY), self::F_SEARCH_KEY); + $radio->setInfo($this->parent_gui->txt(self::F_SEARCH_KEY . '_info')); + + $opt = new ilRadioOption($this->parent_gui->txt(self::F_FLAVOR), self::F_FLAVOR); + $te = new ilTextInputGUI('', self::F_FLAVOR); + $te->setInfo($this->parent_gui->txt(self::F_FLAVOR . '_info')); + $opt->addSubItem($te); + $radio->addOption($opt); + + $opt = new ilRadioOption($this->parent_gui->txt(self::F_TAG), self::F_TAG); + $te = new ilTextInputGUI('', self::F_TAG); + $opt->addSubItem($te); + $radio->addOption($opt); + + $radio->setValue(self::F_FLAVOR); + $this->addItem($radio); + + //F_MEDIATYPE + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_MEDIATYPE), self::F_MEDIATYPE); + $te->setInfo($this->parent_gui->txt(self::F_MEDIATYPE . '_info')); + $this->addItem($te); + + if (in_array( + $this->object->getParentUsageId(), + [PublicationUsage::USAGE_DOWNLOAD, PublicationUsage::USAGE_DOWNLOAD_FALLBACK], + true + )) { + $allow_multiple = new ilCheckboxInputGUI($this->parent_gui->txt(self::F_ALLOW_MULTIPLE), self::F_ALLOW_MULTIPLE); + $allow_multiple->setInfo($this->parent_gui->txt(self::F_ALLOW_MULTIPLE . '_info')); + //F_IGNORE_OBJECT_SETTINGS + $ignore_object_setting = new ilCheckboxInputGUI( + $this->parent_gui->txt(self::F_IGNORE_OBJECT_SETTINGS), + self::F_IGNORE_OBJECT_SETTINGS + ); + $ignore_object_setting->setInfo($this->parent_gui->txt(self::F_IGNORE_OBJECT_SETTINGS . '_info')); + //F_EXT_DL_SOURCE + $ext_dl_source = new ilCheckboxInputGUI( + $this->parent_gui->txt(self::F_EXT_DL_SOURCE), + self::F_EXT_DL_SOURCE + ); + $ext_dl_source->setInfo($this->parent_gui->txt(self::F_EXT_DL_SOURCE . '_info')); + } else { + $allow_multiple = new ilHiddenInputGUI(self::F_ALLOW_MULTIPLE); + $allow_multiple->setValue(0); + $ignore_object_setting = new ilHiddenInputGUI(self::F_IGNORE_OBJECT_SETTINGS); + $ignore_object_setting->setValue(0); + $ext_dl_source = new ilHiddenInputGUI(self::F_EXT_DL_SOURCE); + $ext_dl_source->setValue(0); + } + $this->addItem($allow_multiple); + $this->addItem($ignore_object_setting); + $this->addItem($ext_dl_source); + } + + + /** + * + */ + public function fillForm() + { + $array = [ + self::F_PARENT_USAGE_ID => $this->object->getParentUsageId(), + self::F_TITLE => $this->object->getTitle(), + self::F_DISPLAY_NAME => $this->object->getDisplayName(), + self::F_DESCRIPTION => $this->object->getDescription(), + self::F_GROUP_ID => $this->object->getGroupId(), + self::F_CHANNEL => $this->object->getChannel(), + self::F_SEARCH_KEY => $this->object->getSearchKey(), + self::F_FLAVOR => $this->object->getFlavor(), + self::F_TAG => $this->object->getTag(), + self::F_MD_TYPE => $this->object->getMdType(), + self::F_ALLOW_MULTIPLE => $this->object->isAllowMultiple(), + self::F_MEDIATYPE => $this->object->getMediaType(), + self::F_IGNORE_OBJECT_SETTINGS => $this->object->ignoreObjectSettings(), + self::F_EXT_DL_SOURCE => $this->object->isExternalDownloadSource(), + ]; + + $this->setValuesByArray($array); + } + + + /** + * returns whether checkinput was successful or not. + * + * @return bool + */ + public function fillObject(): bool + { + if (!$this->checkInput()) { + return false; + } + + $this->object->setParentUsageId($this->getInput(self::F_PARENT_USAGE_ID)); + $this->object->setTitle($this->getInput(self::F_TITLE)); + $this->object->setDisplayName($this->getInput(self::F_DISPLAY_NAME)); + $this->object->setDescription($this->getInput(self::F_DESCRIPTION)); + $this->object->setGroupId($this->getInput(self::F_GROUP_ID)); + $this->object->setChannel($this->getInput(self::F_CHANNEL)); + $this->object->setSearchKey($this->getInput(self::F_SEARCH_KEY)); + $this->object->setFlavor($this->getInput(self::F_FLAVOR)); + $this->object->setTag($this->getInput(self::F_TAG)); + $this->object->setMdType($this->getInput(self::F_MD_TYPE)); + $this->object->setAllowMultiple((bool)$this->getInput(self::F_ALLOW_MULTIPLE)); + $this->object->setMediaType($this->getInput(self::F_MEDIATYPE)); + $this->object->setIgnoreObjectSettings((bool)$this->getInput(self::F_IGNORE_OBJECT_SETTINGS)); + $this->object->setExternalDownloadSource((bool)$this->getInput(self::F_EXT_DL_SOURCE)); + + return true; + } + + + /** + * @return bool + */ + public function saveObject(): bool + { + if (!$this->fillObject()) { + return false; + } + if ($this->is_new) { + $this->object->create(); + } else { + $this->object->update(); + } + + return true; + } + + + /** + * + */ + protected function initButtons() + { + if ($this->is_new) { + $this->setTitle($this->parent_gui->txt('create_sub')); + $this->addCommandButton( + xoctPublicationUsageGUI::CMD_CREATE_SUB, + $this->parent_gui->txt(xoctPublicationUsageGUI::CMD_CREATE) + ); + } else { + $this->setTitle($this->parent_gui->txt('edit_sub')); + $this->addCommandButton( + xoctPublicationUsageGUI::CMD_UPDATE_SUB, + $this->parent_gui->txt(xoctPublicationUsageGUI::CMD_UPDATE) + ); + } + + $this->addCommandButton(xoctPublicationUsageGUI::CMD_CANCEL, $this->parent_gui->txt(xoctPublicationUsageGUI::CMD_CANCEL)); + } +} diff --git a/classes/Conf/PublicationUsage/class.xoctPublicationSubUsageTableGUI.php b/classes/Conf/PublicationUsage/class.xoctPublicationSubUsageTableGUI.php new file mode 100644 index 000000000..0a0e2faca --- /dev/null +++ b/classes/Conf/PublicationUsage/class.xoctPublicationSubUsageTableGUI.php @@ -0,0 +1,176 @@ + + */ +class xoctPublicationSubUsageTableGUI extends ilTable2GUI +{ + public const TBL_ID = 'tbl_xoct_pub_sub_u'; + /** + * @var array + */ + protected $filter = []; + + /** + * @var ilOpenCastPlugin + */ + protected $plugin; + /** + * @var OpencastDIC + */ + protected $container; + + /** + * @param xoctPublicationUsageGUI $a_parent_obj + * @param string $a_parent_cmd + */ + public function __construct(xoctPublicationUsageGUI $a_parent_obj, $a_parent_cmd) + { + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->container = OpencastDIC::getInstance(); + $this->plugin = $this->container->plugin(); + $this->setId(self::TBL_ID); + $this->setPrefix(self::TBL_ID); + $this->setFormName(self::TBL_ID); + $this->ctrl->saveParameter($a_parent_obj, $this->getNavParameter()); + $this->parent_obj = $a_parent_obj; + $this->setTitle($this->parent_obj->txt('table_title_sub_usage')); + $this->setRowTemplate( + 'tpl.publication_sub_usage.html', + 'Customizing/global/plugins/Services/Repository/RepositoryObject/OpenCast' + ); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->initColumns(); + $this->parseData(); + } + + + /** + * @param array $a_set + * + * @throws DICException + */ + public function fillRow($a_set) + { + /** + * @var $publication_sub_usage PublicationSubUsage + */ + $publication_sub_usage = PublicationSubUsage::find($a_set['id']); + $this->tpl->setVariable('PARENT_USAGE_ID', $publication_sub_usage->getParentUsageId()); + $this->tpl->setVariable('TITLE', $publication_sub_usage->getTitle()); + $this->tpl->setVariable('DISPLAY_NAME', $publication_sub_usage->getDisplayName()); + $this->tpl->setVariable('DESCRIPTION', $publication_sub_usage->getDescription()); + $this->tpl->setVariable('CHANNEL', $publication_sub_usage->getChannel()); + $this->tpl->setVariable('MD_TYPE', $this->parent_obj->txt('md_type_' . $publication_sub_usage->getMdType())); + if ($publication_sub_usage->getMdType() === PublicationUsage::MD_TYPE_PUBLICATION_ITSELF) { + $this->tpl->setVariable('FLAVOR', ' '); + $this->tpl->setVariable('TAG', ' '); + } elseif ($publication_sub_usage->getSearchKey() == xoctPublicationUsageFormGUI::F_FLAVOR) { + $this->tpl->setVariable('FLAVOR', $publication_sub_usage->getFlavor()); + $this->tpl->setVariable('TAG', ' '); + } else { + $this->tpl->setVariable('TAG', $publication_sub_usage->getTag()); + $this->tpl->setVariable('FLAVOR', ' '); + } + $group_name = ''; + if (!is_null($publication_sub_usage->getGroupId())) { + $publication_usage_group = PublicationUsageGroup::find($publication_sub_usage->getGroupId()); + $group_name = $publication_usage_group ? $publication_usage_group->getName() : $group_name; + } + $this->tpl->setVariable('GROUP_NAME', $group_name); + + $extras = []; + if ($publication_sub_usage->getParentUsageId() == PublicationUsage::USAGE_DOWNLOAD || + $publication_sub_usage->getParentUsageId() == PublicationUsage::USAGE_DOWNLOAD_FALLBACK) { + if ($publication_sub_usage->isExternalDownloadSource()) { + $extras[] = $this->parent_obj->txt('ext_dl_source'); + } + } + $this->tpl->setVariable('EXTRA_CONFIG', implode('
', $extras)); + + $this->addActionMenu($publication_sub_usage); + } + + + protected function initColumns() + { + $this->addColumn($this->parent_obj->txt('parent_usage_id')); + $this->addColumn($this->parent_obj->txt('title')); + $this->addColumn($this->parent_obj->txt('display_name')); + $this->addColumn($this->parent_obj->txt('description')); + $this->addColumn($this->parent_obj->txt('channel')); + $this->addColumn($this->parent_obj->txt('md_type')); + $this->addColumn($this->parent_obj->txt('flavor')); + $this->addColumn($this->parent_obj->txt('tag')); + $this->addColumn($this->parent_obj->txt('group_th')); + $this->addColumn($this->parent_obj->txt('extra_config')); + + $this->addColumn($this->plugin->txt('common_actions'), '', '150px'); + } + + + /** + * @param PublicationSubUsage $publication_sub_usage + * + * @throws DICException + */ + protected function addActionMenu(PublicationSubUsage $publication_sub_usage) + { + $current_selection_list = new ilAdvancedSelectionListGUI(); + $current_selection_list->setListTitle($this->plugin->txt('common_actions')); + $current_selection_list->setId(self::TBL_ID . '_actions_' . $publication_sub_usage->getId()); + $current_selection_list->setUseImages(false); + + $this->ctrl->setParameter($this->parent_obj, 'id', $publication_sub_usage->getId()); + $current_selection_list->addItem( + $this->parent_obj->txt(xoctPublicationUsageGUI::CMD_EDIT), + xoctPublicationUsageGUI::CMD_EDIT_SUB, + $this->ctrl->getLinkTarget($this->parent_obj, xoctPublicationUsageGUI::CMD_EDIT_SUB) + ); + $current_selection_list->addItem( + $this->parent_obj->txt(xoctPublicationUsageGUI::CMD_DELETE), + xoctPublicationUsageGUI::CMD_DELETE_SUB, + $this->ctrl->getLinkTarget($this->parent_obj, xoctPublicationUsageGUI::CMD_CONFIRM_DELETE_SUB) + ); + + $this->tpl->setVariable('ACTIONS', $current_selection_list->getHTML()); + } + + + protected function parseData() + { + $subs = PublicationSubUsage::getArray(); + // Sorting by parent usage id. + usort($subs, function ($sub1, $sub2) { + return strcmp($sub1['parent_usage_id'], $sub2['parent_usage_id']); + }); + // Sorting by title. + usort($subs, function ($sub1, $sub2) { + return strcmp($sub1['title'], $sub2['title']); + }); + $this->setData($subs); + } + + + /** + * @param $item + */ + protected function addAndReadFilterItem(ilFormPropertyGUI $item) + { + $this->addFilterItem($item); + $item->readFromSession(); + if ($item instanceof ilCheckboxInputGUI) { + $this->filter[$item->getPostVar()] = $item->getChecked(); + } else { + $this->filter[$item->getPostVar()] = $item->getValue(); + } + } +} diff --git a/classes/Conf/PublicationUsage/class.xoctPublicationUsageFormGUI.php b/classes/Conf/PublicationUsage/class.xoctPublicationUsageFormGUI.php index 583efc1f3..153943038 100644 --- a/classes/Conf/PublicationUsage/class.xoctPublicationUsageFormGUI.php +++ b/classes/Conf/PublicationUsage/class.xoctPublicationUsageFormGUI.php @@ -1,6 +1,8 @@ ctrl(); + $this->container = OpencastDIC::getInstance(); + $this->plugin = $this->container->plugin(); $DIC->ui()->mainTemplate()->addJavaScript( - ilOpenCastPlugin::getInstance()->getDirectory() . '/templates/default/publication_usage_form.min.js' + $this->plugin->getDirectory() . '/js/opencast/dist/index.js' ); + $DIC->ui()->mainTemplate()->addOnLoadCode('il.Opencast.Form.publicationUsage.init()'); parent::__construct(); $this->object = $xoctPublicationUsage; $this->parent_gui = $parent_gui; + $this->parent_gui->setTab(); $ctrl->saveParameter($parent_gui, xoctPublicationUsageGUI::IDENTIFIER); $this->is_new = ($this->object->getUsageId() == ''); $this->initForm(); @@ -70,9 +89,26 @@ protected function initForm() $te->setRequired(true); $this->addItem($te); + // F_DISPLAY_NAME + $max_lenght = 20; + $display_name = (!empty($this->object->getDisplayName()) ? $this->object->getDisplayName() : '{added display name}'); + $info = sprintf($this->parent_gui->txt(self::F_DISPLAY_NAME . '_info'), $max_lenght, strtolower($display_name)); + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_DISPLAY_NAME), self::F_DISPLAY_NAME); + $te->setInfo($info); + $te->setMaxLength($max_lenght); + $this->addItem($te); + $te = new ilTextAreaInputGUI($this->parent_gui->txt(self::F_DESCRIPTION), self::F_DESCRIPTION); $this->addItem($te); + // F_GROUP_ID + $xoctPublicationUsageGroupsArray = PublicationUsageGroup::getArray('id', 'name'); + $empty_groups = ['' => '-']; + $publication_groups = $empty_groups + $xoctPublicationUsageGroupsArray; + $te = new ilSelectInputGUI($this->parent_gui->txt(self::F_GROUP_ID), self::F_GROUP_ID); + $te->setOptions($publication_groups); + $this->addItem($te); + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_CHANNEL), self::F_CHANNEL); $te->setRequired(true); $this->addItem($te); @@ -107,19 +143,41 @@ protected function initForm() $radio->setValue(self::F_FLAVOR); $this->addItem($radio); + //F_MEDIATYPE + $te = new ilTextInputGUI($this->parent_gui->txt(self::F_MEDIATYPE), self::F_MEDIATYPE); + $te->setInfo($this->parent_gui->txt(self::F_MEDIATYPE . '_info')); + $this->addItem($te); + if (in_array( $this->object->getUsageId(), - [PublicationUsage::USAGE_DOWNLOAD, PublicationUsage::USAGE_DOWNLOAD_FALLBACK] + [PublicationUsage::USAGE_DOWNLOAD, PublicationUsage::USAGE_DOWNLOAD_FALLBACK], + true )) { - $allow_multiple = new ilCheckboxInputGUI( - $this->parent_gui->txt(self::F_ALLOW_MULTIPLE), - self::F_ALLOW_MULTIPLE + $allow_multiple = new ilCheckboxInputGUI($this->parent_gui->txt(self::F_ALLOW_MULTIPLE), self::F_ALLOW_MULTIPLE); + $allow_multiple->setInfo($this->parent_gui->txt(self::F_ALLOW_MULTIPLE . '_info')); + //F_IGNORE_OBJECT_SETTINGS + $ignore_object_setting = new ilCheckboxInputGUI( + $this->parent_gui->txt(self::F_IGNORE_OBJECT_SETTINGS), + self::F_IGNORE_OBJECT_SETTINGS + ); + $ignore_object_setting->setInfo($this->parent_gui->txt(self::F_IGNORE_OBJECT_SETTINGS . '_info')); + //F_EXT_DL_SOURCE + $ext_dl_source = new ilCheckboxInputGUI( + $this->parent_gui->txt(self::F_EXT_DL_SOURCE), + self::F_EXT_DL_SOURCE ); + $ext_dl_source->setInfo($this->parent_gui->txt(self::F_EXT_DL_SOURCE . '_info')); } else { $allow_multiple = new ilHiddenInputGUI(self::F_ALLOW_MULTIPLE); $allow_multiple->setValue(0); + $ignore_object_setting = new ilHiddenInputGUI(self::F_IGNORE_OBJECT_SETTINGS); + $ignore_object_setting->setValue(0); + $ext_dl_source = new ilHiddenInputGUI(self::F_EXT_DL_SOURCE); + $ext_dl_source->setValue(0); } $this->addItem($allow_multiple); + $this->addItem($ignore_object_setting); + $this->addItem($ext_dl_source); } /** @@ -130,13 +188,18 @@ public function fillForm(): void $array = [ self::F_USAGE_ID => $this->object->getUsageId(), self::F_TITLE => $this->object->getTitle(), + self::F_DISPLAY_NAME => $this->object->getDisplayName(), self::F_DESCRIPTION => $this->object->getDescription(), + self::F_GROUP_ID => $this->object->getGroupId(), self::F_CHANNEL => $this->object->getChannel(), self::F_SEARCH_KEY => $this->object->getSearchKey(), self::F_FLAVOR => $this->object->getFlavor(), self::F_TAG => $this->object->getTag(), self::F_MD_TYPE => $this->object->getMdType(), self::F_ALLOW_MULTIPLE => $this->object->isAllowMultiple(), + self::F_MEDIATYPE => $this->object->getMediaType(), + self::F_IGNORE_OBJECT_SETTINGS => $this->object->ignoreObjectSettings(), + self::F_EXT_DL_SOURCE => $this->object->isExternalDownloadSource(), ]; $this->setValuesByArray($array); @@ -153,13 +216,18 @@ public function fillObject(): bool $this->object->setUsageId($this->getInput(self::F_USAGE_ID)); $this->object->setTitle($this->getInput(self::F_TITLE)); + $this->object->setDisplayName($this->getInput(self::F_DISPLAY_NAME)); $this->object->setDescription($this->getInput(self::F_DESCRIPTION)); + $this->object->setGroupId($this->getInput(self::F_GROUP_ID)); $this->object->setChannel($this->getInput(self::F_CHANNEL)); $this->object->setSearchKey($this->getInput(self::F_SEARCH_KEY)); $this->object->setFlavor($this->getInput(self::F_FLAVOR)); $this->object->setTag($this->getInput(self::F_TAG)); $this->object->setMdType($this->getInput(self::F_MD_TYPE)); $this->object->setAllowMultiple((bool) $this->getInput(self::F_ALLOW_MULTIPLE)); + $this->object->setMediaType($this->getInput(self::F_MEDIATYPE)); + $this->object->setIgnoreObjectSettings((bool) $this->getInput(self::F_IGNORE_OBJECT_SETTINGS)); + $this->object->setExternalDownloadSource((bool)$this->getInput(self::F_EXT_DL_SOURCE)); return true; } diff --git a/classes/Conf/PublicationUsage/class.xoctPublicationUsageGUI.php b/classes/Conf/PublicationUsage/class.xoctPublicationUsageGUI.php index 25c614861..9d274cdf9 100644 --- a/classes/Conf/PublicationUsage/class.xoctPublicationUsageGUI.php +++ b/classes/Conf/PublicationUsage/class.xoctPublicationUsageGUI.php @@ -1,7 +1,10 @@ http = $DIC->http(); $this->toolbar = $DIC->toolbar(); $this->main_tpl = $DIC->ui()->mainTemplate(); + $this->tabs = $DIC->tabs(); + // Getting Query Parameters + $this->pub_subtab_active = + $this->http->request()->getQueryParams()['pub_subtab_active'] ?? xoctMainGUI::SUBTAB_PUBLICATION_USAGE; + $this->identifier = $this->http->request()->getQueryParams()[self::IDENTIFIER] ?? ''; + if (!empty($this->http->request()->getParsedBody()[self::IDENTIFIER])) { + $this->identifier = $this->http->request()->getParsedBody()[self::IDENTIFIER]; + } + $this->get_id = (int) $this->http->request()->getQueryParams()['id'] ?? null; + $this->post_id = (int) $this->http->request()->getParsedBody()['id'] ?? null; + $this->channel = $this->http->request()->getParsedBody()[xoctPublicationUsageFormGUI::F_CHANNEL] ?? null; $this->repository = new PublicationUsageRepository(); + $this->sub_repository = new PublicationSubUsageRepository(); + $this->setTab(); } /** @@ -44,14 +105,49 @@ public function __construct() */ protected function index() { - if ($this->repository->getMissingUsageIds() !== []) { + $xoctPublicationTabsTableGUI = $this->initTabTableGUI($this->pub_subtab_active); + $this->main_tpl->setContent($xoctPublicationTabsTableGUI->getHTML()); + } + + /** + * Helps setting the tabs at all time. + */ + public function setTab() + { + $this->ctrl->saveParameter($this, 'pub_subtab_active'); + $this->tabs->setSubTabActive($this->pub_subtab_active); + } + + + /** + * Decides which content to display for the current tab. + * @return ilTable2GUI + */ + protected function initTabTableGUI($pub_subtab_active): ilTable2GUI + { + if ($pub_subtab_active === xoctMainGUI::SUBTAB_PUBLICATION_USAGE) { + if (count($this->repository->getMissingUsageIds()) > 0) { + $b = ilLinkButton::getInstance(); + $b->setCaption($this->plugin->getPrefix() . '_publication_usage_add_new'); + $b->setUrl($this->ctrl->getLinkTarget($this, self::CMD_SELECT_PUBLICATION_ID)); + $this->toolbar->addButtonInstance($b); + } + return new xoctPublicationUsageTableGUI($this, self::CMD_STANDARD); + } elseif ($pub_subtab_active === xoctMainGUI::SUBTAB_PUBLICATION_SUB_USAGE) { + if (count($this->repository->getSubAllowedUsageIds()) > 0) { + $b = ilLinkButton::getInstance(); + $b->setCaption($this->plugin->getPrefix() . '_publication_usage_add_new_sub'); + $b->setUrl($this->ctrl->getLinkTarget($this, self::CMD_SELECT_PUBLICATION_ID_SUB)); + $this->toolbar->addButtonInstance($b); + } + return new xoctPublicationSubUsageTableGUI($this, self::CMD_STANDARD); + } elseif ($pub_subtab_active === xoctMainGUI::SUBTAB_PUBLICATION_GROUPS) { $b = ilLinkButton::getInstance(); - $b->setCaption($this->plugin->getPrefix() . '_publication_usage_add_new'); - $b->setUrl($this->ctrl->getLinkTarget($this, self::CMD_SELECT_PUBLICATION_ID)); + $b->setCaption($this->plugin->getPrefix() . '_publication_usage_add_new_group'); + $b->setUrl($this->ctrl->getLinkTarget($this, self::CMD_ADD_NEW_GROUP)); $this->toolbar->addButtonInstance($b); + return new xoctPublicationGroupTableGUI($this, self::CMD_STANDARD); } - $xoctPublicationUsageTableGUI = new xoctPublicationUsageTableGUI($this, self::CMD_STANDARD); - $this->main_tpl->setContent($xoctPublicationUsageTableGUI->getHTML()); } /** @@ -83,12 +179,12 @@ protected function selectPublicationId() */ protected function add() { - if (!$_POST[xoctPublicationUsageFormGUI::F_CHANNEL]) { + if (!$this->channel) { $this->ctrl->redirect($this, self::CMD_SELECT_PUBLICATION_ID); } $xoctPublicationUsage = new PublicationUsage(); - $xoctPublicationUsage->setUsageId($_POST[xoctPublicationUsageFormGUI::F_CHANNEL]); - $xoctPublicationUsage->setTitle($this->txt('type_' . $_POST[xoctPublicationUsageFormGUI::F_CHANNEL])); + $xoctPublicationUsage->setUsageId($this->channel); + $xoctPublicationUsage->setTitle($this->txt('type_' . $this->channel)); $xoctPublicationUsageFormGUI = new xoctPublicationUsageFormGUI($this, $xoctPublicationUsage); $xoctPublicationUsageFormGUI->fillForm(); $this->main_tpl->setContent($xoctPublicationUsageFormGUI->getHTML()); @@ -113,9 +209,13 @@ protected function create() */ protected function edit() { + if (empty($this->identifier)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_no_identifier'), true); + $this->ctrl->redirect($this); + } $xoctPublicationUsageFormGUI = new xoctPublicationUsageFormGUI( $this, - $this->repository->getUsage($_GET[self::IDENTIFIER]) + $this->repository->getUsage($this->identifier) ); $xoctPublicationUsageFormGUI->fillForm(); $this->main_tpl->setContent($xoctPublicationUsageFormGUI->getHTML()); @@ -126,10 +226,13 @@ protected function edit() */ protected function update() { - $usage_id = $_GET[self::IDENTIFIER]; + $publication_usage = new PublicationUsage(); + if (!$this->identifier && $this->repository->getUsage($this->identifier)) { + $publication_usage = $this->repository->getUsage($this->identifier); + } $xoctPublicationUsageFormGUI = new xoctPublicationUsageFormGUI( $this, - $usage_id ? $this->repository->getUsage($_GET[self::IDENTIFIER]) : new PublicationUsage() + $publication_usage ); $xoctPublicationUsageFormGUI->setValuesByPost(); if ($xoctPublicationUsageFormGUI->saveObject()) { @@ -154,10 +257,14 @@ public function txt($key): string */ protected function confirmDelete() { + if (empty($this->identifier)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_no_identifier'), true); + $this->ctrl->redirect($this); + } /** * @var $xoctPublicationUsage PublicationUsage */ - $xoctPublicationUsage = $this->repository->getUsage($_GET[self::IDENTIFIER]); + $xoctPublicationUsage = $this->repository->getUsage($this->identifier); $confirm = new ilConfirmationGUI(); $confirm->addItem(self::IDENTIFIER, $xoctPublicationUsage->getUsageId(), $xoctPublicationUsage->getTitle()); $confirm->setFormAction($this->ctrl->getFormAction($this)); @@ -172,7 +279,210 @@ protected function confirmDelete() */ protected function delete() { - $this->repository->delete($_POST[self::IDENTIFIER]); + $this->repository->delete($this->identifier); + $this->cancel(); + } + + + ### Subs Section ### + /** + * Helps select the sub usage channel. + * INFO: Although there is only Download channel available to select, but there is the capability to extend this feature + * for other channels too. + */ + protected function selectPublicationIdForSub() + { + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->txt('select_sub_usage_id')); + $form->setDescription($this->txt('select_sub_usage_id_desc')); + $form->addCommandButton(self::CMD_ADD_SUB, $this->txt(self::CMD_ADD)); + $form->addCommandButton(self::CMD_CANCEL, $this->txt(self::CMD_CANCEL)); + $sel = new ilSelectInputGUI($this->txt(xoctPublicationUsageFormGUI::F_CHANNEL), xoctPublicationUsageFormGUI::F_CHANNEL); + $options = []; + foreach ($this->repository->getSubAllowedUsageIds() as $id) { + $options[$id] = $this->txt('type_' . $id); + } + $sel->setOptions($options); + + $form->addItem($sel); + $this->main_tpl->setContent($form->getHTML()); + } + + /** + * + */ + protected function addSub() + { + $channel = $this->channel; + if (empty($channel) || !in_array($channel, $this->repository->getSubAllowedUsageIds(), true)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_sub_not_allowed'), true); + $this->ctrl->redirect($this, self::CMD_SELECT_PUBLICATION_ID_SUB); + } + $xoctPublicationSubUsage = new PublicationSubUsage(); + $xoctPublicationSubUsage->setParentUsageId($channel); + $title_text = $this->txt('type_' . $channel); + $title = $this->sub_repository->generateTitle($channel, $title_text); + $xoctPublicationSubUsage->setTitle($title); + $xoctPublicationSubUsageFormGUI = new xoctPublicationSubUsageFormGUI($this, $xoctPublicationSubUsage); + $xoctPublicationSubUsageFormGUI->fillForm(); + $this->main_tpl->setContent($xoctPublicationSubUsageFormGUI->getHTML()); + } + + /** + * @throws DICException + */ + protected function createSub() + { + $xoctPublicationSubUsageFormGUI = new xoctPublicationSubUsageFormGUI($this, new PublicationSubUsage()); + $xoctPublicationSubUsageFormGUI->setValuesByPost(); + if ($xoctPublicationSubUsageFormGUI->saveObject()) { + ilUtil::sendSuccess($this->plugin->txt('publication_usage_msg_success_sub'), true); + $this->ctrl->redirect($this); + } + $this->main_tpl->setContent($xoctPublicationSubUsageFormGUI->getHTML()); + } + + /** + * + */ + protected function editSub() + { + if (!PublicationSubUsage::find($this->get_id)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_sub_not_found'), true); + $this->ctrl->redirect($this); + } + $xoctPublicationSubUsageFormGUI = new xoctPublicationSubUsageFormGUI($this, PublicationSubUsage::find($this->get_id), false); + $xoctPublicationSubUsageFormGUI->fillForm(); + $this->main_tpl->setContent($xoctPublicationSubUsageFormGUI->getHTML()); + } + + + /** + * @throws DICException + */ + protected function updateSub() + { + $sub_usage_id = $this->get_id; + if (!PublicationSubUsage::find($sub_usage_id)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_sub_not_found'), true); + $this->ctrl->redirect($this); + } + $xoctPublicationSubUsageFormGUI = new xoctPublicationSubUsageFormGUI( + $this, + PublicationSubUsage::find($sub_usage_id), + false + ); + $xoctPublicationSubUsageFormGUI->setValuesByPost(); + if ($xoctPublicationSubUsageFormGUI->saveObject()) { + ilUtil::sendSuccess($this->plugin->txt('publication_usage_msg_success_sub'), true); + $this->ctrl->redirect($this); + } + $this->main_tpl->setContent($xoctPublicationSubUsageFormGUI->getHTML()); + } + + protected function confirmDeleteSub() + { + if (!PublicationSubUsage::find($this->get_id)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_sub_not_found'), true); + $this->ctrl->redirect($this); + } + $xoctPublicationSubUsage = PublicationSubUsage::find($this->get_id); + $confirm = new ilConfirmationGUI(); + $confirm->setHeaderText($this->txt('confirm_delete_text_sub')); + $confirm->addItem('id', $this->get_id, $xoctPublicationSubUsage->getTitle()); + $confirm->setFormAction($this->ctrl->getFormAction($this)); + $confirm->setCancel($this->txt(self::CMD_CANCEL), self::CMD_CANCEL); + $confirm->setConfirm($this->txt(self::CMD_DELETE), self::CMD_DELETE_SUB); + + $this->main_tpl->setContent($confirm->getHTML()); + } + + protected function deleteSub() + { + if (!PublicationSubUsage::find($this->post_id)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_sub_not_found'), true); + $this->ctrl->redirect($this); + } + + $xoctPublicationSubUsage = PublicationSubUsage::find($this->post_id); + $xoctPublicationSubUsage->delete(); + $this->cancel(); + } + + ### End Subs Section ### + + ### Group Section ### + + protected function addNewGroup() + { + $xoctPublicationUsageGroup = new PublicationUsageGroup(); + $xoctPublicationGroupFormGUI = new xoctPublicationGroupFormGUI($this, $xoctPublicationUsageGroup); + $xoctPublicationGroupFormGUI->setFormAction($this->ctrl->getFormAction($this)); + $xoctPublicationGroupFormGUI->fillForm(); + $this->main_tpl->setContent($xoctPublicationGroupFormGUI->getHTML()); + } + + protected function createGroup() + { + $xoctPublicationGroupFormGUI = new xoctPublicationGroupFormGUI($this, new PublicationUsageGroup()); + $xoctPublicationGroupFormGUI->setValuesByPost(); + if ($xoctPublicationGroupFormGUI->saveObject()) { + ilUtil::sendSuccess($this->plugin->txt('publication_usage_msg_success'), true); + $this->ctrl->redirect($this); + } + $this->main_tpl->setContent($xoctPublicationGroupFormGUI->getHTML()); + } + + protected function editGroup() + { + if (!PublicationUsageGroup::find($this->get_id)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_group_not_found'), true); + $this->ctrl->redirect($this); + } + $xoctPublicationGroupFormGUI = new xoctPublicationGroupFormGUI($this, PublicationUsageGroup::find($this->get_id), false); + $xoctPublicationGroupFormGUI->fillForm(); + $this->main_tpl->setContent($xoctPublicationGroupFormGUI->getHTML()); + } + + protected function updateGroup() + { + $xoctPublicationGroupFormGUI = new xoctPublicationGroupFormGUI($this, PublicationUsageGroup::find($this->get_id), false); + $xoctPublicationGroupFormGUI->setValuesByPost(); + if ($xoctPublicationGroupFormGUI->saveObject()) { + ilUtil::sendSuccess($this->plugin->txt('publication_usage_msg_success'), true); + $this->ctrl->redirect($this); + } + $this->main_tpl->setContent($xoctPublicationGroupFormGUI->getHTML()); + } + + protected function confirmDeleteGroup() + { + if (!PublicationUsageGroup::find($this->get_id)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_group_not_found'), true); + $this->ctrl->redirect($this); + } + $xoctPublicationUsageGroup = PublicationUsageGroup::find($this->get_id); + $confirm = new ilConfirmationGUI(); + $confirm->setHeaderText($this->txt('confirm_delete_text_group')); + $confirm->addItem('id', $this->get_id, $xoctPublicationUsageGroup->getName()); + $confirm->setFormAction($this->ctrl->getFormAction($this)); + $confirm->setCancel($this->txt(self::CMD_CANCEL), self::CMD_CANCEL); + $confirm->setConfirm($this->txt(self::CMD_DELETE), self::CMD_DELETE_GROUP); + + $this->main_tpl->setContent($confirm->getHTML()); + } + + protected function deleteGroup() + { + if (!PublicationUsageGroup::find($this->post_id)) { + ilUtil::sendFailure($this->plugin->txt('publication_usage_group_not_found'), true); + $this->ctrl->redirect($this); + } + + $xoctPublicationUsageGroup = PublicationUsageGroup::find($this->post_id); + $xoctPublicationUsageGroup->delete(); $this->cancel(); } + ### End Group Section ### } diff --git a/classes/Conf/PublicationUsage/class.xoctPublicationUsageTableGUI.php b/classes/Conf/PublicationUsage/class.xoctPublicationUsageTableGUI.php index 5e8deb034..601779067 100755 --- a/classes/Conf/PublicationUsage/class.xoctPublicationUsageTableGUI.php +++ b/classes/Conf/PublicationUsage/class.xoctPublicationUsageTableGUI.php @@ -2,6 +2,7 @@ use srag\Plugins\Opencast\Model\Publication\Config\PublicationUsage; use srag\Plugins\Opencast\Model\Publication\Config\PublicationUsageRepository; +use srag\Plugins\Opencast\Model\Publication\Config\PublicationUsageGroup; use srag\Plugins\Opencast\DI\OpencastDIC; /** @@ -49,6 +50,7 @@ public function __construct(xoctPublicationUsageGUI $a_parent_obj, $a_parent_cmd $this->ctrl->saveParameter($a_parent_obj, $this->getNavParameter()); parent::__construct($a_parent_obj, $a_parent_cmd); $this->parent_obj = $a_parent_obj; + $this->setTitle($this->parent_obj->txt('table_title_usage')); $this->setRowTemplate( 'tpl.publication_usage.html', 'Customizing/global/plugins/Services/Repository/RepositoryObject/OpenCast' @@ -66,38 +68,56 @@ public function __construct(xoctPublicationUsageGUI $a_parent_obj, $a_parent_cmd protected function fillRow($a_set) { /** - * @var $PublicationUsage PublicationUsage + * @var $publication_usage PublicationUsage */ - $PublicationUsage = $this->repository->getUsage($a_set['usage_id']); - $this->tpl->setVariable('USAGE_ID', $PublicationUsage->getUsageId()); - $this->tpl->setVariable('TITLE', $PublicationUsage->getTitle()); - $this->tpl->setVariable('DESCRIPTION', $PublicationUsage->getDescription()); - $this->tpl->setVariable('CHANNEL', $PublicationUsage->getChannel()); - $this->tpl->setVariable('MD_TYPE', $this->parent_obj->txt('md_type_' . $PublicationUsage->getMdType())); - if ($PublicationUsage->getMdType() === PublicationUsage::MD_TYPE_PUBLICATION_ITSELF) { + $publication_usage = $this->repository->getUsage($a_set['usage_id']); + $this->tpl->setVariable('USAGE_ID', $publication_usage->getUsageId()); + $this->tpl->setVariable('TITLE', $publication_usage->getTitle()); + $this->tpl->setVariable('DISPLAY_NAME', $publication_usage->getDisplayName()); + $this->tpl->setVariable('DESCRIPTION', $publication_usage->getDescription()); + $this->tpl->setVariable('CHANNEL', $publication_usage->getChannel()); + $this->tpl->setVariable('MD_TYPE', $this->parent_obj->txt('md_type_' . $publication_usage->getMdType())); + if ($publication_usage->getMdType() === PublicationUsage::MD_TYPE_PUBLICATION_ITSELF) { $this->tpl->setVariable('FLAVOR', ' '); $this->tpl->setVariable('TAG', ' '); - } elseif ($PublicationUsage->getSearchKey() == xoctPublicationUsageFormGUI::F_FLAVOR) { - $this->tpl->setVariable('FLAVOR', $PublicationUsage->getFlavor()); + } elseif ($publication_usage->getSearchKey() == xoctPublicationUsageFormGUI::F_FLAVOR) { + $this->tpl->setVariable('FLAVOR', $publication_usage->getFlavor()); $this->tpl->setVariable('TAG', ' '); } else { - $this->tpl->setVariable('TAG', $PublicationUsage->getTag()); + $this->tpl->setVariable('TAG', $publication_usage->getTag()); $this->tpl->setVariable('FLAVOR', ' '); } + $group_name = ''; + if (!is_null($publication_usage->getGroupId())) { + $publication_usage_group = PublicationUsageGroup::find($publication_usage->getGroupId()); + $group_name = $publication_usage_group ? $publication_usage_group->getName() : $group_name; + } + $this->tpl->setVariable('GROUP_NAME', $group_name); + + $extras = []; + if ($publication_usage->getUsageId() == PublicationUsage::USAGE_DOWNLOAD || + $publication_usage->getUsageId() == PublicationUsage::USAGE_DOWNLOAD_FALLBACK) { + if ($publication_usage->isExternalDownloadSource()) { + $extras[] = $this->parent_obj->txt('ext_dl_source'); + } + } + $this->tpl->setVariable('EXTRA_CONFIG', implode('
', $extras)); - $this->addActionMenu($PublicationUsage); + $this->addActionMenu($publication_usage); } protected function initColumns() { $this->addColumn($this->parent_obj->txt('usage_id')); $this->addColumn($this->parent_obj->txt('title')); + $this->addColumn($this->parent_obj->txt('display_name')); $this->addColumn($this->parent_obj->txt('description')); $this->addColumn($this->parent_obj->txt('channel')); $this->addColumn($this->parent_obj->txt('md_type')); $this->addColumn($this->parent_obj->txt('flavor')); $this->addColumn($this->parent_obj->txt('tag')); - // $this->addColumn($this->txt('status')); + $this->addColumn($this->parent_obj->txt('group_th')); + $this->addColumn($this->parent_obj->txt('extra_config')); $this->addColumn($this->plugin->txt('common_actions'), '', '150px'); } diff --git a/classes/Conf/class.xoctConfFormGUI.php b/classes/Conf/class.xoctConfFormGUI.php index ab25c9f4b..b7a531028 100644 --- a/classes/Conf/class.xoctConfFormGUI.php +++ b/classes/Conf/class.xoctConfFormGUI.php @@ -44,7 +44,7 @@ public function __construct(xoctConfGUI $parent_gui, $subtab_active) $container = OpencastDIC::getInstance(); $this->main_tpl = $DIC->ui()->mainTemplate(); $this->plugin = $container->plugin(); - $this->main_tpl->addJavaScript($this->plugin->getDirectory().'/js/opencast/dist/index.js'); + $this->main_tpl->addJavaScript($this->plugin->getDirectory() . '/js/opencast/dist/index.js'); $this->main_tpl->addCss($this->plugin->getStyleSheetLocation('default/password_toggle.css')); parent::__construct(); $this->parent_gui = $parent_gui; @@ -258,13 +258,6 @@ protected function initEventsSection(): void $cb->setInfo($this->parent_gui->txt(PluginConfig::F_CREATE_SCHEDULED_ALLOWED . '_info')); $this->addItem($cb); - $cb = new ilCheckboxInputGUI( - $this->parent_gui->txt(PluginConfig::F_EXT_DL_SOURCE), - PluginConfig::F_EXT_DL_SOURCE - ); - $cb->setInfo($this->parent_gui->txt(PluginConfig::F_EXT_DL_SOURCE . '_info')); - $this->addItem($cb); - $cb = new ilCheckboxInputGUI( $this->parent_gui->txt(PluginConfig::F_STUDIO_ALLOWED), PluginConfig::F_STUDIO_ALLOWED @@ -717,16 +710,19 @@ protected function initAdvancedSection() ); $cb->addOption($opt); $opt = new ilRadioOption( - $this->parent_gui->txt(PluginConfig::F_ACTIVATE_CACHE . '_' . PluginConfig::CACHE_STANDARD), - PluginConfig::CACHE_STANDARD + $this->parent_gui->txt(PluginConfig::F_ACTIVATE_CACHE . '_' . PluginConfig::CACHE_APCU), + PluginConfig::CACHE_APCU ); $opt->setInfo( $this->parent_gui->txt( - PluginConfig::F_ACTIVATE_CACHE . '_' . PluginConfig::CACHE_STANDARD . '_info', + PluginConfig::F_ACTIVATE_CACHE . '_' . PluginConfig::CACHE_APCU . '_info', '', [] ) ); + $apc_available = !function_exists('apcu_fetch'); + $opt->setDisabled($apc_available); + $cb->addOption($opt); $opt = new ilRadioOption( $this->parent_gui->txt(PluginConfig::F_ACTIVATE_CACHE . '_' . PluginConfig::CACHE_DATABASE), diff --git a/classes/Event/class.xoctEventGUI.php b/classes/Event/class.xoctEventGUI.php index 0f2c1f04d..bb3790fa3 100755 --- a/classes/Event/class.xoctEventGUI.php +++ b/classes/Event/class.xoctEventGUI.php @@ -4,7 +4,6 @@ use ILIAS\UI\Component\Input\Field\UploadHandler; use ILIAS\UI\Renderer; use srag\Plugins\Opencast\Model\ACL\ACLUtils; -use srag\Plugins\Opencast\Model\Cache\CacheFactory; use srag\Plugins\Opencast\Model\Config\PluginConfig; use srag\Plugins\Opencast\Model\Event\Event; use srag\Plugins\Opencast\Model\Event\EventRepository; @@ -38,6 +37,7 @@ use srag\Plugins\OpenCast\UI\Component\Input\Field\Loader; use srag\CustomInputGUIs\OneDrive\Waiter\Waiter; use srag\Plugins\Opencast\API\OpencastAPI; +use srag\Plugins\Opencast\Model\Cache\Services; /** * Class xoctEventGUI @@ -73,6 +73,14 @@ class xoctEventGUI extends xoctGUI * @var ilObjOpenCastGUI */ private $parent_gui; + /** + * @var WaitOverlay + */ + private $wait_overlay; + /** + * @var Services + */ + private $cache; /** * @var \ILIAS\UI\Implementation\DefaultRenderer */ @@ -169,7 +177,7 @@ public function __construct( PaellaConfigServiceFactory $paellaConfigServiceFactory, Container $dic ) { - global $DIC; + global $DIC, $opencastContainer; parent::__construct(); $this->user = $DIC->user(); @@ -193,6 +201,8 @@ public function __construct( $this->ui_renderer = new \ILIAS\UI\Implementation\DefaultRenderer( new Loader($DIC, ilOpenCastPlugin::getInstance()) ); + $this->wait_overlay = new WaitOverlay($this->main_tpl); + $this->cache = $opencastContainer->get(Services::class); } /** @@ -284,8 +294,7 @@ protected function performCommand($cmd) */ protected function prepareContent() { - xoctWaiterGUI::initJS(); - xoctWaiterGUI::addLinkOverlay('#rep_robj_xoct_event_clear_cache'); + $this->wait_overlay->onLinkClick('#rep_robj_xoct_event_clear_cache'); $this->main_tpl->addJavascript("./src/UI/templates/js/Modal/modal.js"); $this->main_tpl->addOnLoadCode( 'xoctEvent.init(\'' . json_encode([ @@ -514,11 +523,11 @@ protected function loadAjaxCodeForList() url: '{$ajax_link}', dataType: 'html', success: function(data){ - xoctWaiter.hide(); + il.Opencast.UI.waitOverlay.hide(); $('div#xoct_table_placeholder').replaceWith($(data)); } });"; - $this->main_tpl->addOnLoadCode('xoctWaiter.show();'); + $this->main_tpl->addOnLoadCode('il.Opencast.UI.waitOverlay.show();'); $this->main_tpl->addOnLoadCode($ajax); } @@ -534,11 +543,11 @@ protected function loadAjaxCodeForTiles() url: '{$ajax_link}', dataType: 'html', success: function(data){ - xoctWaiter.hide(); + il.Opencast.UI.waitOverlay.hide(); $('div#xoct_tiles_placeholder').replaceWith($(data)); } });"; - $this->main_tpl->addOnLoadCode('xoctWaiter.show();'); + $this->main_tpl->addOnLoadCode('il.Opencast.UI.waitOverlay.show();'); $this->main_tpl->addOnLoadCode($ajax); } @@ -625,12 +634,8 @@ protected function add() $this->objectSettings->getObjId(), ilObjOpenCastAccess::hasPermission('edit_videos') ); - xoctWaiterGUI::initJS(); - $this->main_tpl->addOnLoadCode( - 'window.onbeforeunload = function(){ - xoctWaiter.show(); - };' - ); + $this->wait_overlay->onUnload(); + $this->main_tpl->setContent($this->ui_renderer->render($form)); } @@ -674,7 +679,7 @@ protected function create() $this->ACLUtils->getBaseACLForUser(xoctUser::getInstance($this->user)), new Processing( PluginConfig::getConfig(PluginConfig::F_WORKFLOW), - $this->getDefaultWorkflowParameters($data['workflow_configuration']['object']) + $this->getDefaultWorkflowParameters($data['workflow_configuration']['object'] ?? null) ), xoctUploadFile::getInstanceFromFileArray($data['file']['file']) ) @@ -906,21 +911,43 @@ public function download(): void { $event_id = filter_input(INPUT_GET, 'event_id', FILTER_SANITIZE_STRING); $publication_id = filter_input(INPUT_GET, 'pub_id', FILTER_SANITIZE_STRING); + $usage_type = filter_input(INPUT_GET, 'usage_type', FILTER_SANITIZE_STRING); + $usage_id = filter_input(INPUT_GET, 'usage_id', FILTER_SANITIZE_STRING); $event = $this->event_repository->find($event_id); $download_publications = $event->publications()->getDownloadPublications(); + // Now that we have multiple sub-usages, we first check for publication_id which is passed by the multi-dropdowns. if ($publication_id) { $publication = array_filter($download_publications, function ($publication) use ($publication_id): bool { return $publication->getId() === $publication_id; }); - $publication = array_shift($publication); + $publication = reset($publication); } else { - $publication = array_shift($download_publications); + // If this is not multi-download dropdown, then it has to have the usage_type and usage_id parameters identified. + if (!empty($usage_type) && !empty($usage_id)) { + $publication = array_filter( + $download_publications, + function ($publication) use ($usage_type, $usage_id): bool { + return $publication->usage_id == $usage_id && $publication->usage_type === $usage_type; + } + ); + $publication = reset($publication); + } else { + // As a fallback we take out the last publication, if non of the above has been met! + $publication = reset($download_publications); + } + } + + if (empty($publication)) { + ilUtil::sendFailure($this->txt('msg_no_download_publication'), true); + $this->ctrl->redirect($this, self::CMD_STANDARD); } + $url = $publication->getUrl(); $extension = pathinfo($url)['extension']; $url = PluginConfig::getConfig(PluginConfig::F_SIGN_DOWNLOAD_LINKS) ? xoctSecureLink::signDownload($url) : $url; - if (PluginConfig::getConfig(PluginConfig::F_EXT_DL_SOURCE)) { + // if (PluginConfig::getConfig(PluginConfig::F_EXT_DL_SOURCE)) { + if (property_exists($publication, 'ext_dl_source') && $publication->ext_dl_source == true) { // Open external source page header('Location: ' . $url); } else { @@ -1222,12 +1249,9 @@ private function unpublish(Event $event): bool return true; } - /** - * - */ - protected function clearCache() + protected function clearCache(): void { - CacheFactory::getInstance()->flush(); + $this->cache->flushAdapter(); $this->ctrl->redirect($this, self::CMD_STANDARD); } diff --git a/classes/Event/class.xoctEventRenderer.php b/classes/Event/class.xoctEventRenderer.php index 3c57e06ab..2ddc28fba 100644 --- a/classes/Event/class.xoctEventRenderer.php +++ b/classes/Event/class.xoctEventRenderer.php @@ -9,10 +9,15 @@ use srag\Plugins\Opencast\Model\Object\ObjectSettings; use srag\Plugins\Opencast\Model\PerVideoPermission\PermissionGrant; use srag\Plugins\Opencast\Model\Publication\Config\PublicationUsage; +use srag\Plugins\Opencast\Model\Publication\Config\PublicationUsageGroup; +use srag\Plugins\Opencast\Model\Publication\Config\PublicationUsageGroupRepository; use srag\Plugins\Opencast\Model\Publication\Config\PublicationUsageRepository; +use srag\Plugins\Opencast\Model\Publication\Config\PublicationSubUsageRepository; use srag\Plugins\Opencast\Model\User\xoctUser; use srag\Plugins\Opencast\UI\Modal\EventModals; +use srag\Plugins\Opencast\Model\DTO\DownloadDto; use srag\Plugins\Opencast\LegacyHelpers\TranslatorTrait; +use srag\Plugins\Opencast\Util\Locale\LocaleTrait; /** * Class xoctEventRenderer @@ -22,6 +27,7 @@ class xoctEventRenderer { use TranslatorTrait; + use LocaleTrait; public const LANG_MODULE = 'event'; /** @@ -53,6 +59,10 @@ class xoctEventRenderer * @var EventModals */ protected static $modals; + /** + * @var array + */ + private $dropdowns; /** * @var \ilCtrlInterface */ @@ -79,6 +89,7 @@ public function __construct(Event $event, ?ObjectSettings $objectSettings = null $this->objectSettings = $objectSettings; $this->factory = $ui->factory(); $this->renderer = $ui->renderer(); + $this->dropdowns = []; } public static function initModals(EventModals $modals): void @@ -105,6 +116,59 @@ public function insert(&$tpl, $variable, $value, $block_title = ''): void } } + /** + * Renders the dropdowns, in case the items to display is in a publication usage group. + * If a group has only one item, it renders it as normal that is why tpl is passed as reference. + * @param $tpl ilTemplate + */ + public function renderDropdowns(&$tpl): void + { + $value = ''; + $sorted_list = []; + if (!empty($this->dropdowns)) { + $sorted_list = PublicationUsageGroupRepository::getSortedArrayList(array_keys($this->dropdowns)); + } + foreach ($sorted_list as $group_id => $group_data) { + $dropdown_contents = $this->dropdowns[$group_id]; + if (count($dropdown_contents) > 1) { + $items = []; + foreach ($dropdown_contents as $content) { + $items[] = $this->factory->link()->standard( + $content['display_name'], + $content['link'] + ); + } + $display_name = $this->getLocaleString( + strtolower($group_data['display_name']), + PublicationUsageGroup::DISPLAY_NAME_LANG_MODULE, + $group_data['display_name'] + ); + if (empty($display_name)) { + $display_name = $this->getLocaleString('default', PublicationUsageGroup::DISPLAY_NAME_LANG_MODULE); + } + $dropdown = $this->factory->dropdown()->standard( + $items + )->withLabel($display_name); + $value .= $this->renderer->renderAsync($dropdown); + } else { + $content = reset($dropdown_contents); + $this->insert($tpl, $content['variable'], $content['html'], $content['block_title']); + continue; + } + } + + if (!empty($value)) { + $block_title_dpdn = 'dropdown'; + $variable_dpdb = 'DROPDOWN'; + $tpl->setCurrentBlock($block_title_dpdn); + + $tpl->setVariable($variable_dpdb, $value); + + $tpl->parseCurrentBlock(); + } + } + + /** * @param $tpl ilTemplate * @param string $block_title @@ -246,18 +310,54 @@ public function getModalLink(): string * @throws ilTemplateException * @throws xoctException */ - public function insertDownloadLink( - &$tpl, - $block_title = 'link', - $variable = 'LINK', - $button_type = 'btn-info' - ): void { - if ($download_link_html = $this->getDownloadLinkHTML($button_type)) { - $this->insert($tpl, $variable, $download_link_html, $block_title); + public function insertDownloadLink(&$tpl, $block_title = 'link', $variable = 'LINK', $button_type = 'btn-info'): void + { + $publication_repository = new PublicationUsageRepository(); + $publication_sub_repository = new PublicationSubUsageRepository(); + $categorized_download_dtos = $this->event->publications()->getDownloadDtos(false); + foreach ($categorized_download_dtos as $usage_type => $content) { + foreach ($content as $usage_id => $download_dtos) { + $download_pub_usage = null; + $display_name = ''; + if ($usage_type == PublicationUsage::USAGE_TYPE_ORG) { + $download_pub_usage = $publication_repository->getUsage($usage_id); + $display_name = $publication_repository->getDisplayName($usage_id); + } else { + $download_pub_usage = $publication_sub_repository->convertSingleSubToUsage($usage_id); + $display_name = $publication_sub_repository->getDisplayName($usage_id); + } + + if (is_null($download_pub_usage)) { + continue; + } + + if (empty($display_name)) { + $display_name = $this->translate('download', self::LANG_MODULE); + } + + $download_html = $this->getDownloadLinkHTML($download_pub_usage, $download_dtos, $display_name, $button_type); + if (!empty($download_html)) { + $group_id = $download_pub_usage->getGroupId(); + if (!is_null($group_id) && !$download_pub_usage->isAllowMultiple()) { + $this->dropdowns[$group_id][] = [ + 'variable' => $variable, + 'display_name' => $display_name, + 'link' => $this->ctrl->getLinkTargetByClass(xoctEventGUI::class, xoctEventGUI::CMD_DOWNLOAD), + 'html' => $download_html, + 'block_title' => $block_title, + ]; + } else { + $this->insert($tpl, $variable, $download_html, $block_title); + } + } + } } } /** + * @param PublicationUsage $download_publication_usage + * @param DownloadDto[] $download_dtos + * @param string $display_name * @param string $button_type * * @return string @@ -265,17 +365,35 @@ public function insertDownloadLink( * @throws ilTemplateException * @throws xoctException */ - public function getDownloadLinkHTML($button_type = 'btn_info') - { - $download_dtos = $this->event->publications()->getDownloadDtos(false); - if (($this->event->getProcessingState() == Event::STATE_SUCCEEDED) && ($download_dtos !== [])) { - if ($this->objectSettings instanceof ObjectSettings && $this->objectSettings->getStreamingOnly()) { + public function getDownloadLinkHTML( + $download_publication_usage, + $download_dtos, + $display_name, + $button_type = 'btn_info' + ): string { + $html = ''; + $ignore_object_settings = $download_publication_usage->ignoreObjectSettings(); + $has_streaming_only = $this->objectSettings instanceof ObjectSettings && $this->objectSettings->getStreamingOnly(); + $show_download = true; + if ($has_streaming_only && $ignore_object_settings == false) { + $show_download = false; + } + if (($this->event->getProcessingState() == Event::STATE_SUCCEEDED) && (count($download_dtos) > 0)) { + if (!$show_download) { return ''; } - $multi = (new PublicationUsageRepository())->getUsage(PublicationUsage::USAGE_DOWNLOAD)->isAllowMultiple(); + + // Setting event_id is necessary, because we use it for both multi approach with pub_id or subusage approach with usage_type and usage_id. + $this->ctrl->setParameterByClass(xoctEventGUI::class, 'event_id', $this->event->getIdentifier()); + + // Setting the floowing parameters to null first, so that we get accurate parameters later on in download action. + $this->ctrl->setParameterByClass(xoctEventGUI::class, 'pub_id', null); + $this->ctrl->setParameterByClass(xoctEventGUI::class, 'usage_type', null); + $this->ctrl->setParameterByClass(xoctEventGUI::class, 'usage_id', null); + + $multi = $download_publication_usage->isAllowMultiple(); if ($multi) { $items = array_map(function ($dto): \ILIAS\UI\Component\Link\Standard { - $this->ctrl->setParameterByClass(xoctEventGUI::class, 'event_id', $this->event->getIdentifier()); $this->ctrl->setParameterByClass(xoctEventGUI::class, 'pub_id', $dto->getPublicationId()); return $this->factory->link()->standard( $dto->getResolution(), @@ -284,22 +402,25 @@ public function getDownloadLinkHTML($button_type = 'btn_info') }, $download_dtos); $dropdown = $this->factory->dropdown()->standard( $items - )->withLabel($this->plugin->txt(self::LANG_MODULE . '_download')); - return $this->ui->renderer()->renderAsync($dropdown); + )->withLabel($display_name); + $html = $this->renderer->renderAsync($dropdown); } else { - $this->ctrl->setParameterByClass(xoctEventGUI::class, 'event_id', $this->event->getIdentifier()); + $usage_type = $download_publication_usage->isSub() ? 'sub' : 'org'; + $this->ctrl->setParameterByClass(xoctEventGUI::class, 'usage_type', $usage_type); + $usage_id = $usage_type === 'sub' ? $download_publication_usage->getSubId() : + $download_publication_usage->getUsageId(); + $this->ctrl->setParameterByClass(xoctEventGUI::class, 'usage_id', $usage_id); $link = $this->ctrl->getLinkTargetByClass(xoctEventGUI::class, xoctEventGUI::CMD_DOWNLOAD); $link_tpl = $this->plugin->getTemplate('default/tpl.player_link.html'); $link_tpl->setVariable('TARGET', '_self'); $link_tpl->setVariable('BUTTON_TYPE', $button_type); - $link_tpl->setVariable('LINK_TEXT', $this->plugin->txt(self::LANG_MODULE . '_download')); + $link_tpl->setVariable('LINK_TEXT', $display_name); $link_tpl->setVariable('LINK_URL', $link); - return $link_tpl->get(); + $html = $link_tpl->get(); } - } else { - return ''; } + return $html; } /** @@ -312,13 +433,21 @@ public function getDownloadLinkHTML($button_type = 'btn_info') * @throws ilTemplateException * @throws xoctException */ - public function insertAnnotationLink( - &$tpl, - $block_title = 'link', - $variable = 'LINK', - $button_type = 'btn-info' - ): void { - if ($annotation_link_html = $this->getAnnotationLinkHTML($button_type)) { + public function insertAnnotationLink(&$tpl, $block_title = 'link', $variable = 'LINK', $button_type = 'btn-info'): void + { + list($display_name, $annotation_link_html) = $this->getAnnotationLinkHTML($button_type); + if (!empty($annotation_link_html)) { + $annotatePublicationUsage = (new PublicationUsageRepository())->getUsage(PublicationUsage::USAGE_ANNOTATE); + $group_id = $annotatePublicationUsage->getGroupId(); + if (!is_null($group_id)) { + $this->dropdowns[$group_id][] = [ + 'variable' => $variable, + 'display_name' => $display_name, + 'link' => $this->ctrl->getLinkTargetByClass(xoctEventGUI::class, xoctEventGUI::CMD_ANNOTATE), + 'block_title' => $block_title, + ]; + return; + } $this->insert($tpl, $variable, $annotation_link_html, $block_title); } } @@ -326,13 +455,18 @@ public function insertAnnotationLink( /** * @param string $button_type * - * @return string + * @return array * @throws DICException * @throws ilTemplateException * @throws xoctException */ - public function getAnnotationLinkHTML($button_type = 'btn_info') + public function getAnnotationLinkHTML($button_type = 'btn_info'): array { + $display_name = (new PublicationUsageRepository())->getDisplayName(PublicationUsage::USAGE_ANNOTATE); + if (empty($display_name)) { + $display_name = $this->translate('annotate', self::LANG_MODULE); + } + $html = ''; if (($this->event->getProcessingState() == Event::STATE_SUCCEEDED) && ($this->event->publications()->getAnnotationPublication())) { $this->ctrl->setParameterByClass( @@ -344,13 +478,12 @@ public function getAnnotationLinkHTML($button_type = 'btn_info') $link_tpl = $this->plugin->getTemplate('default/tpl.player_link.html'); $link_tpl->setVariable('TARGET', '_blank'); $link_tpl->setVariable('BUTTON_TYPE', $button_type); - $link_tpl->setVariable('LINK_TEXT', $this->plugin->txt(self::LANG_MODULE . '_annotate')); + $link_tpl->setVariable('LINK_TEXT', $display_name); $link_tpl->setVariable('LINK_URL', $annotations_link); - return $link_tpl->get(); - } else { - return ''; + $html = $link_tpl->get(); } + return [$display_name, $html]; } /** @@ -671,7 +804,8 @@ public function getActions(): array $this->plugin->txt('event_startworkflow'), self::$modals->getStartworkflowModal()->getShowSignal() )->withOnLoadCode(function ($id) { - return "$({$id}).on('click', function(event){ $('input#startworkflow_event_id').val('{$this->event->getIdentifier()}'); $('.startworkflow-form select#workflow_id').val(''); $('.startworkflow-form select#workflow_id').trigger('change');});"; + return "$({$id}).on('click'," . + "function(event){ $('input#republish_event_id').val('{$this->event->getIdentifier()}'); });"; }); } @@ -723,7 +857,9 @@ public function getActions(): array $this->plugin->txt('event_report_quality_problem'), self::$modals->getReportQualityModal()->getShowSignal() )->withOnLoadCode(function ($id) { - return "$({$id}).on('click', function(event){ $('input#xoct_report_quality_event_id').val('{$this->event->getIdentifier()}');$('#xoct_report_quality_modal textarea#message').focus(); });"; + return "$({$id}).on('click', function(event){ " . + "$('input#xoct_report_quality_event_id').val('{$this->event->getIdentifier()}');" . + "$('#xoct_report_quality_modal textarea#message').focus(); });"; }); } diff --git a/classes/Event/class.xoctEventTableGUI.php b/classes/Event/class.xoctEventTableGUI.php index 6c62b8f22..7937fc68a 100755 --- a/classes/Event/class.xoctEventTableGUI.php +++ b/classes/Event/class.xoctEventTableGUI.php @@ -165,9 +165,8 @@ protected function fillRow($a_set) $renderer->insertPreviewImage($this->tpl, null); $renderer->insertPlayerLink($this->tpl); - if (!$this->object_settings->getStreamingOnly()) { - $renderer->insertDownloadLink($this->tpl); - } + // The object settings will be checked based from within the insertDownloadLink method! + $renderer->insertDownloadLink($this->tpl); if ($this->object_settings->getUseAnnotations()) { $renderer->insertAnnotationLink($this->tpl); @@ -195,6 +194,10 @@ protected function fillRow($a_set) $renderer->insertUnprotectedLink($this->tpl, 'generic', 'VALUE'); } + // In order to render dropdowns, we have to call its method here (at the end), + // because the dropdown list gets its value during the call of download and annotate insertion. + $renderer->renderDropdowns($this->tpl); + $this->addActionMenu($event); } diff --git a/classes/Event/class.xoctEventTileGUI.php b/classes/Event/class.xoctEventTileGUI.php index bc0ca4cf0..fe006ad75 100644 --- a/classes/Event/class.xoctEventTileGUI.php +++ b/classes/Event/class.xoctEventTileGUI.php @@ -126,12 +126,18 @@ public function getHTML() $buttons_tpl = $this->plugin->getTemplate('default/tpl.event_buttons.html'); $event_renderer->insertPlayerLink($buttons_tpl, 'link', 'LINK', 'btn-default'); - if (!$this->objectSettings->getStreamingOnly()) { - $event_renderer->insertDownloadLink($buttons_tpl, 'link', 'LINK', 'btn-default'); - } + + // The object settings will be checked based from within the insertDownloadLink method! + $event_renderer->insertDownloadLink($buttons_tpl, 'link', 'LINK', 'btn-default'); + if ($this->objectSettings->getUseAnnotations()) { $event_renderer->insertAnnotationLink($buttons_tpl, 'link', 'LINK', 'btn-default'); } + + // In order to render dropdowns, we have to call its method here (at the end), + // because the dropdown list gets its value during the call of download and annotate insertion. + $event_renderer->renderDropdowns($buttons_tpl); + $tile_tpl->setVariable('EVENT_BUTTONS', $buttons_tpl->get()); $card = $this->factory->card()->repositoryObject( diff --git a/classes/IVTGroup/class.xoctPermissionGroupGUI.php b/classes/IVTGroup/class.xoctPermissionGroupGUI.php index 102222f54..36c016b01 100644 --- a/classes/IVTGroup/class.xoctPermissionGroupGUI.php +++ b/classes/IVTGroup/class.xoctPermissionGroupGUI.php @@ -42,8 +42,9 @@ public function __construct(?ObjectSettings $objectSettings = null) $this->objectSettings = new ObjectSettings(); } $tabs->setTabActive(ilObjOpenCastGUI::TAB_GROUPS); - // xoctGroup::installDB(); - xoctWaiterGUI::loadLib(); + + new WaitOverlay($this->main_tpl); // TODO check if needed + $main_tpl->addCss($this->plugin->getStyleSheetLocation('default/groups.css')); $main_tpl->addJavaScript($this->plugin->getStyleSheetLocation('default/groups.js')); } diff --git a/classes/IVTGroup/class.xoctPermissionGroupParticipantGUI.php b/classes/IVTGroup/class.xoctPermissionGroupParticipantGUI.php index 6ed3e8b67..181b1484a 100644 --- a/classes/IVTGroup/class.xoctPermissionGroupParticipantGUI.php +++ b/classes/IVTGroup/class.xoctPermissionGroupParticipantGUI.php @@ -35,7 +35,9 @@ public function __construct(?ObjectSettings $objectSettings = null) $this->objectSettings = new ObjectSettings(); } $tabs->setTabActive(ilObjOpenCastGUI::TAB_GROUPS); - xoctWaiterGUI::loadLib(); + + new WaitOverlay($main_tpl); // TODO check if needed + $main_tpl->addJavaScript( $this->plugin->getStyleSheetLocation('default/group_participants.js') ); diff --git a/classes/Invitations/class.xoctGrantPermissionGUI.php b/classes/Invitations/class.xoctGrantPermissionGUI.php index 1dfc8d8b7..00a2c61ce 100644 --- a/classes/Invitations/class.xoctGrantPermissionGUI.php +++ b/classes/Invitations/class.xoctGrantPermissionGUI.php @@ -51,7 +51,7 @@ public function __construct(ObjectSettings $objectSettings, EventRepository $eve $tabs->clearTargets(); $tabs->setBackTarget($this->plugin->txt('tab_back'), $this->ctrl->getLinkTargetByClass(xoctEventGUI::class)); - xoctWaiterGUI::loadLib(); + new WaitOverlay($this->main_tpl); // TODO check if needed $main_tpl->addCss($this->plugin->getStyleSheetLocation('default/invitations.css')); $main_tpl->addJavaScript($this->plugin->getStyleSheetLocation('default/invitations.js')); $this->ctrl->saveParameter($this, xoctEventGUI::IDENTIFIER); diff --git a/classes/Owner/class.xoctChangeOwnerGUI.php b/classes/Owner/class.xoctChangeOwnerGUI.php index 68290d3b2..a7f43471e 100644 --- a/classes/Owner/class.xoctChangeOwnerGUI.php +++ b/classes/Owner/class.xoctChangeOwnerGUI.php @@ -60,7 +60,9 @@ public function __construct(ObjectSettings $objectSettings, EventRepository $eve $this->plugin->txt('tab_back'), $ctrl->getLinkTargetByClass(xoctEventGUI::class) ); - xoctWaiterGUI::loadLib(); + + new WaitOverlay($this->main_tpl); // TODO check if needed + $main_tpl->addCss($this->plugin->getStyleSheetLocation('default/change_owner.css')); $main_tpl->addJavaScript($this->plugin->getStyleSheetLocation('default/change_owner.js')); $ctrl->saveParameter($this, xoctEventGUI::IDENTIFIER); diff --git a/classes/Service/class.xoctEventAPI.php b/classes/Service/class.xoctEventAPI.php index 0cd1326cb..beabdb14f 100644 --- a/classes/Service/class.xoctEventAPI.php +++ b/classes/Service/class.xoctEventAPI.php @@ -47,8 +47,9 @@ class xoctEventAPI public function __construct() { + global $opencastContainer; + $this->event_repository = $opencastContainer[EventAPIRepository::class]; $opencastDIC = OpencastDIC::getInstance(); - $this->event_repository = $opencastDIC->event_repository(); $this->md_factory = $opencastDIC->metadata()->metadataFactory(); $this->acl_utils = $opencastDIC->acl_utils(); $this->workflow_param_repository = $opencastDIC->workflow_parameter_series_repository(); diff --git a/classes/Service/class.xoctSeriesAPI.php b/classes/Service/class.xoctSeriesAPI.php index fa3aee56b..e0504bcb4 100644 --- a/classes/Service/class.xoctSeriesAPI.php +++ b/classes/Service/class.xoctSeriesAPI.php @@ -15,6 +15,7 @@ use srag\Plugins\Opencast\Model\Series\SeriesRepository; use srag\Plugins\Opencast\Model\User\xoctUser; use srag\Plugins\Opencast\Model\WorkflowParameter\Series\SeriesWorkflowParameterRepository; +use srag\Plugins\Opencast\Model\Series\SeriesAPIRepository; /** * Class xoctSeriesAPI @@ -51,8 +52,9 @@ class xoctSeriesAPI */ public function __construct() { + global $opencastContainer; + $this->series_repository = $opencastContainer->get(SeriesAPIRepository::class); $opencastDIC = OpencastDIC::getInstance(); - $this->series_repository = $opencastDIC->series_repository(); $this->seriesWorkflowParameterRepository = $opencastDIC->workflow_parameter_series_repository(); $this->metadataFactory = $opencastDIC->metadata()->metadataFactory(); $this->aclUtils = $opencastDIC->acl_utils(); diff --git a/classes/class.ilObjOpenCastGUI.php b/classes/class.ilObjOpenCastGUI.php index d5c8298ff..e9846a3b4 100755 --- a/classes/class.ilObjOpenCastGUI.php +++ b/classes/class.ilObjOpenCastGUI.php @@ -16,6 +16,8 @@ use srag\Plugins\Opencast\Model\Series\Request\CreateSeriesRequestPayload; use srag\Plugins\Opencast\Model\User\xoctUser; use srag\Plugins\Opencast\UI\LegacyFormWrapper; +use srag\Plugins\Opencast\Model\Event\EventAPIRepository; +use srag\Plugins\Opencast\Model\Series\SeriesAPIRepository; /** * User Interface class for example repository object. @@ -30,6 +32,9 @@ */ class ilObjOpenCastGUI extends ilObjectPluginGUI { + /** + * @var mixed + */ public $creation_mode; public const PLUGIN_CLASS_NAME = ilOpenCastPlugin::class; @@ -61,16 +66,16 @@ class ilObjOpenCastGUI extends ilObjectPluginGUI * @var Container */ private $ilias_dic; + /** + * @var \srag\Plugins\Opencast\Container\Container + */ + private $container; - private function cleanUpDBCache(): void + public function __construct($a_ref_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) { - if (PluginConfig::getConfig(PluginConfig::F_ACTIVATE_CACHE) == PluginConfig::CACHE_DATABASE) { - $bm = microtime(true); - DBCacheService::cleanup($this->ilias_dic->database()); - $this->ilias_dic->logger()->root()->info( - 'cache cleanup done in ' . round((microtime(true) - $bm) * 1000) . 'ms' - ); - } + parent::__construct($a_ref_id, $a_id_type, $a_parent_node_id); + global $opencastContainer; + $this->container = $opencastContainer; } protected function afterConstructor() @@ -120,7 +125,7 @@ public function executeCommand(): void $this->setTabs(); $xoctGrantPermissionGUI = new xoctGrantPermissionGUI( $objectSettings, - $this->opencast_dic->event_repository(), + $this->container[EventAPIRepository::class], $this->opencast_dic->acl_utils() ); $this->ilias_dic->ctrl()->forwardCommand($xoctGrantPermissionGUI); @@ -131,7 +136,7 @@ public function executeCommand(): void $this->setTabs(); $xoctChangeOwnerGUI = new xoctChangeOwnerGUI( $objectSettings, - $this->opencast_dic->event_repository(), + $this->container[EventAPIRepository::class], $this->opencast_dic->acl_utils() ); $this->ilias_dic->ctrl()->forwardCommand($xoctChangeOwnerGUI); @@ -143,7 +148,7 @@ public function executeCommand(): void $xoctSeriesGUI = new xoctSeriesGUI( $this->object, $this->opencast_dic->series_form_builder(), - $this->opencast_dic->series_repository(), + $this->container->get(SeriesAPIRepository::class), $this->opencast_dic->workflow_parameter_series_repository(), $this->opencast_dic->workflow_parameter_conf_repository() ); @@ -156,12 +161,12 @@ public function executeCommand(): void $xoctEventGUI = new xoctEventGUI( $this, $objectSettings, - $this->opencast_dic->event_repository(), + $this->container[EventAPIRepository::class], $this->opencast_dic->event_form_builder(), $this->opencast_dic->event_table_builder(), $this->opencast_dic->workflow_repository(), $this->opencast_dic->acl_utils(), - $this->opencast_dic->series_repository(), + $this->container->get(SeriesAPIRepository::class), $this->opencast_dic->upload_handler(), $this->opencast_dic->paella_config_storage_service(), $this->opencast_dic->paella_config_service_factory(), @@ -199,8 +204,6 @@ public function executeCommand(): void $this->showMainTemplate(); } } - - $this->cleanUpDBCache(); } public function getObject(): ilObjOpenCast @@ -438,7 +441,7 @@ public function afterSave(ilObject $newObj): void } // TODO: do we need contributor / organizer? if (!$series_id) { - $series_id = $this->opencast_dic->series_repository()->create( + $series_id = $this->container->get(SeriesAPIRepository::class)->create( new CreateSeriesRequest( new CreateSeriesRequestPayload( $metadata, @@ -447,7 +450,7 @@ public function afterSave(ilObject $newObj): void ) ); } else { - $metadata = $this->opencast_dic->series_repository()->find($series_id)->getMetadata(); + $metadata = $this->container->get(SeriesAPIRepository::class)->find($series_id)->getMetadata(); } if ($series_id !== null) { @@ -500,7 +503,6 @@ protected function initHeader($render_locator = true) $this->ilias_dic->ui()->mainTemplate()->setTitle($this->object->getTitle()); $this->ilias_dic->ui()->mainTemplate()->setDescription($this->object->getDescription()); if ($this->ilias_dic->access()->checkAccess('read', '', $_GET['ref_id'])) { - // TODO: remove self::dic $DIC['ilNavigationHistory']->addItem( $_GET['ref_id'], $this->ilias_dic->ctrl()->getLinkTarget($this, $this->getStandardCmd()), @@ -557,7 +559,7 @@ public function infoScreen(): void } if ($objectSettings->getVideoPortalLink() - && $this->opencast_dic->series_repository()->find( + && $this->container->get(SeriesAPIRepository::class)->find( $objectSettings->getSeriesIdentifier() )->isPublishedOnVideoPortal()) { $info->addSection($this->plugin->txt('series_links')); diff --git a/classes/class.xoctMainGUI.php b/classes/class.xoctMainGUI.php index 5b06786f6..b9616ecf5 100644 --- a/classes/class.xoctMainGUI.php +++ b/classes/class.xoctMainGUI.php @@ -36,6 +36,10 @@ class xoctMainGUI extends xoctGUI */ private $tabs; + public const SUBTAB_PUBLICATION_USAGE = 'publication_usage'; + public const SUBTAB_PUBLICATION_SUB_USAGE = 'publication_sub_usage'; + public const SUBTAB_PUBLICATION_GROUPS = 'publication_groups'; + public function __construct() { global $DIC; @@ -100,6 +104,7 @@ public function executeCommand(): void switch ($nextClass) { case strtolower(xoctPublicationUsageGUI::class): $this->tabs->activateTab(self::TAB_PUBLICATION_USAGE); + $this->setPublicationSubTabs(); $xoctPublicationUsageGUI = new xoctPublicationUsageGUI(); $this->ctrl->forwardCommand($xoctPublicationUsageGUI); break; @@ -197,6 +202,30 @@ protected function setSubTabs() $this->ctrl->clearParametersByClass(xoctConfGUI::class); } + protected function setPublicationSubTabs() + { + $this->ctrl->setParameterByClass(xoctPublicationUsageGUI::class, 'pub_subtab_active', self::SUBTAB_PUBLICATION_USAGE); + $this->tabs->addSubTab( + self::SUBTAB_PUBLICATION_USAGE, + $this->plugin->txt('subtab_' . self::SUBTAB_PUBLICATION_USAGE), + $this->ctrl->getLinkTargetByClass(xoctPublicationUsageGUI::class) + ); + $this->ctrl->setParameterByClass(xoctPublicationUsageGUI::class, 'pub_subtab_active', self::SUBTAB_PUBLICATION_SUB_USAGE); + $this->tabs->addSubTab( + self::SUBTAB_PUBLICATION_SUB_USAGE, + $this->plugin->txt('subtab_' . self::SUBTAB_PUBLICATION_SUB_USAGE), + $this->ctrl->getLinkTargetByClass(xoctPublicationUsageGUI::class) + ); + $this->ctrl->setParameterByClass(xoctPublicationUsageGUI::class, 'pub_subtab_active', self::SUBTAB_PUBLICATION_GROUPS); + $this->tabs->addSubTab( + self::SUBTAB_PUBLICATION_GROUPS, + $this->plugin->txt('subtab_' . self::SUBTAB_PUBLICATION_GROUPS), + $this->ctrl->getLinkTargetByClass(xoctPublicationUsageGUI::class) + ); + $this->ctrl->clearParametersByClass(xoctPublicationUsageGUI::class); + } + + protected function setWorkflowsSubTabs() { $this->ctrl->setParameterByClass(xoctWorkflowGUI::class, 'wf_subtab_active', self::SUBTAB_WORKFLOWS_SETTINGS); diff --git a/classes/class.xoctWaiterGUI.php b/classes/class.xoctWaiterGUI.php deleted file mode 100644 index 8e99a3d32..000000000 --- a/classes/class.xoctWaiterGUI.php +++ /dev/null @@ -1,85 +0,0 @@ - - * @version 1.0.0 - */ -class xoctWaiterGUI -{ - public const PLUGIN_CLASS_NAME = ilOpenCastPlugin::class; - - /** - * @var bool - */ - protected static $init = false; - /** - * @var bool - */ - protected static $init_js = false; - - /** - * - */ - public static function loadLib(): void - { - global $DIC; - $main_tpl = $DIC->ui()->mainTemplate(); - if (!self::$init) { - $main_tpl->addJavaScript( - './Customizing/global/plugins/Services/Repository/RepositoryObject/OpenCast/templates/default/waiter.min.js' - ); - $main_tpl->addCss( - './Customizing/global/plugins/Services/Repository/RepositoryObject/OpenCast/templates/default/waiter.css' - ); - self::$init = true; - } - } - - /** - * @param string $type - */ - public static function initJS($type = 'waiter'): void - { - global $DIC; - $main_tpl = $DIC->ui()->mainTemplate(); - self::loadLib(); - if (!self::$init_js) { - $code = 'xoctWaiter.init(\'' . $type . '\');'; - $main_tpl->addOnLoadCode($code); - self::$init_js = true; - } - } - - /** - * @param $dom_selector_string - */ - public static function addListener($dom_selector_string): void - { - global $DIC; - $main_tpl = $DIC->ui()->mainTemplate(); - $code = 'xoctWaiter.addListener("' . $dom_selector_string . '");'; - $main_tpl->addOnLoadCode($code); - } - - /** - * @param $dom_selector_string - */ - public static function addLinkOverlay($dom_selector_string): void - { - global $DIC; - $main_tpl = $DIC->ui()->mainTemplate(); - $code = 'xoctWaiter.addLinkOverlay("' . $dom_selector_string . '");'; - $main_tpl->addOnLoadCode($code); - } - - public static function show(): void - { - global $DIC; - $main_tpl = $DIC->ui()->mainTemplate(); - self::initJS(); - $code = 'xoctWaiter.show();'; - $main_tpl->addOnLoadCode($code); - } -} diff --git a/composer.json b/composer.json index 78a693678..e1926aae8 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "prefer-stable": true, "require": { "php": ">=7.3", - "elan-ev/opencast-api": "1.4", + "elan-ev/opencast-api": "1.5", "srag/custominputguis": ">=0.1.0", "srag/datatable": ">=0.1.0", "srag/dic": ">=0.1.0", diff --git a/composer.lock b/composer.lock index a6a5891bd..8f9a9930d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,20 +4,20 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "3ec6035552927b2808b955c9ba4217c5", + "content-hash": "c514e8f9e82f7cdff520698cb95baa64", "packages": [ { "name": "elan-ev/opencast-api", - "version": "1.4.0", + "version": "1.5.0", "source": { "type": "git", "url": "https://github.com/elan-ev/opencast-php-library.git", - "reference": "34b46fb9c0986fc7e4ecd05a45038612da7409c9" + "reference": "dfcfa0789c8a670623ed27434ced88f595941b73" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/elan-ev/opencast-php-library/zipball/34b46fb9c0986fc7e4ecd05a45038612da7409c9", - "reference": "34b46fb9c0986fc7e4ecd05a45038612da7409c9", + "url": "https://api.github.com/repos/elan-ev/opencast-php-library/zipball/dfcfa0789c8a670623ed27434ced88f595941b73", + "reference": "dfcfa0789c8a670623ed27434ced88f595941b73", "shasum": "" }, "require": { @@ -61,9 +61,9 @@ ], "support": { "issues": "https://github.com/elan-ev/opencast-php-library/issues", - "source": "https://github.com/elan-ev/opencast-php-library/tree/1.4.0" + "source": "https://github.com/elan-ev/opencast-php-library/tree/1.5.0" }, - "time": "2023-07-21T11:58:16+00:00" + "time": "2023-11-13T16:47:55+00:00" }, { "name": "guzzlehttp/guzzle", @@ -3227,8 +3227,8 @@ "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": ">=7.0" + "php": ">=7.3" }, "platform-dev": [], - "plugin-api-version": "2.3.0" + "plugin-api-version": "2.6.0" } diff --git a/configuration/default_config.xml b/configuration/default_config.xml index e7ab0afc1..016645a60 100644 --- a/configuration/default_config.xml +++ b/configuration/default_config.xml @@ -262,10 +262,6 @@ workflow_unpublish - - external_download_source - - presenter-mandatory diff --git a/doc/codestyle/run-code-format.sh b/doc/codestyle/run-code-format.sh index 4f5c3195a..f3923a129 100755 --- a/doc/codestyle/run-code-format.sh +++ b/doc/codestyle/run-code-format.sh @@ -5,7 +5,7 @@ if [[ ! -z "$1" ]] then PATHS=$1 else - PATHS=$(git diff --name-only --cached | tr -u '\n' ' ') + PATHS=$(git diff --name-only --cached | xargs ls -d 2>/dev/null | tr -u '\n' ' ') if [[ -z "$PATHS" ]] then PATHS=$TOP_LEVEL diff --git a/js/opencast/dist/index.js b/js/opencast/dist/index.js index ae7febd83..0a5485656 100644 --- a/js/opencast/dist/index.js +++ b/js/opencast/dist/index.js @@ -1 +1 @@ -!function(t,e){"use strict";function n(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=n(t),o=n(e);"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function i(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var a=i(function(t,e,n){return t(n={path:e,exports:{},require:function(t,e){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==e&&n.path)}},n.exports),n.exports}((function(t,e){var n;n=()=>(()=>{var t={383:(t,e,n)=>{n.r(e),n.d(e,{default:()=>f});var r=n(622),o=n(689),i=n.n(o);function a(t){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function s(){s=function(){return t};var t={},e=Object.prototype,n=e.hasOwnProperty,r=Object.defineProperty||function(t,e,n){t[e]=n.value},o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",c=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function f(t,e,n,o){var i=e&&e.prototype instanceof d?e:d,a=Object.create(i.prototype),s=new L(o||[]);return r(a,"_invoke",{value:E(t,n,s)}),a}function h(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}t.wrap=f;var p={};function d(){}function y(){}function v(){}var g={};l(g,i,(function(){return this}));var m=Object.getPrototypeOf,b=m&&m(m(S([])));b&&b!==e&&n.call(b,i)&&(g=b);var w=v.prototype=d.prototype=Object.create(g);function A(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){function o(r,i,s,c){var u=h(t[r],t,i);if("throw"!==u.type){var l=u.arg,f=l.value;return f&&"object"==a(f)&&n.call(f,"__await")?e.resolve(f.__await).then((function(t){o("next",t,s,c)}),(function(t){o("throw",t,s,c)})):e.resolve(f).then((function(t){l.value=t,s(l)}),(function(t){return o("throw",t,s,c)}))}c(u.arg)}var i;r(this,"_invoke",{value:function(t,n){function r(){return new e((function(e,r){o(t,n,e,r)}))}return i=i?i.then(r,r):r()}})}function E(t,e,n){var r="suspendedStart";return function(o,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===o)throw i;return{value:void 0,done:!0}}for(n.method=o,n.arg=i;;){var a=n.delegate;if(a){var s=C(a,n);if(s){if(s===p)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var c=h(t,e,n);if("normal"===c.type){if(r=n.done?"completed":"suspendedYield",c.arg===p)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r="completed",n.method="throw",n.arg=c.arg)}}}function C(t,e){var n=e.method,r=t.iterator[n];if(void 0===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=void 0,C(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),p;var o=h(r,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,p;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,p):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,p)}function k(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function _(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function L(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(k,this),this.reset(!0)}function S(t){if(t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,o=function e(){for(;++r=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),c=n.call(i,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),_(n),p}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;_(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:S(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),p}},t}function c(t,e,n,r,o,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(r,o)}function u(t,e){return(u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function l(t){return(l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var f=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&u(t,e)}(d,t);var e,n,r,o,f,h,p=(f=d,h=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}(),function(){var t,e=l(f);if(h){var n=l(this).constructor;t=Reflect.construct(e,arguments,n)}else t=e.apply(this,arguments);return function(t,e){if(e&&("object"===a(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(this,t)});function d(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,d),p.apply(this,arguments)}return e=d,(n=[{key:"load",value:(r=s().mark((function t(){return s().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:this.icon=this.player.getCustomPluginIcon(this.name,"buttonIcon")||i();case 1:case"end":return t.stop()}}),t,this)})),o=function(){var t=this,e=arguments;return new Promise((function(n,o){var i=r.apply(t,e);function a(t){c(i,n,o,a,s,"next",t)}function s(t){c(i,n,o,a,s,"throw",t)}a(void 0)}))},function(){return o.apply(this,arguments)})}])&&function(t,e){for(var n=0;n0&&e-1 in t)}function L(t,e){return t.nodeName&&t.nodeName.toLowerCase()===e.toLowerCase()}k.fn=k.prototype={jquery:E,constructor:k,length:0,toArray:function(){return s.call(this)},get:function(t){return null==t?s.call(this):t<0?this[t+this.length]:this[t]},pushStack:function(t){var e=k.merge(this.constructor(),t);return e.prevObject=this,e},each:function(t){return k.each(this,t)},map:function(t){return this.pushStack(k.map(this,(function(e,n){return t.call(e,n,e)})))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(k.grep(this,(function(t,e){return(e+1)%2})))},odd:function(){return this.pushStack(k.grep(this,(function(t,e){return e%2})))},eq:function(t){var e=this.length,n=+t+(t<0?e:0);return this.pushStack(n>=0&&n+~]|"+O+")"+O+"*"),G=new RegExp(O+"|>"),H=new RegExp(N),$=new RegExp("^"+I+"$"),V={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+j),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),bool:new RegExp("^(?:"+_+")$","i"),needsContext:new RegExp("^"+O+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)","i")},Z=/^(?:input|select|textarea|button)$/i,z=/^h\d$/i,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Y=/[+~]/,W=new RegExp("\\\\[\\da-fA-F]{1,6}"+O+"?|\\\\([^\\r\\n\\f])","g"),q=function(t,e){var n="0x"+t.slice(1)-65536;return e||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},X=function(){ct()},Q=ht((function(t){return!0===t.disabled&&L(t,"fieldset")}),{dir:"parentNode",next:"legend"});try{y.apply(i=s.call(D.childNodes),D.childNodes),i[D.childNodes.length].nodeType}catch(t){y={apply:function(t,e){B.apply(t,s.call(e))},call:function(t){B.apply(t,s.call(arguments,1))}}}function J(t,e,n,r){var o,i,a,s,u,l,p,d=e&&e.ownerDocument,m=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==m&&9!==m&&11!==m)return n;if(!r&&(ct(e),e=e||c,f)){if(11!==m&&(u=K.exec(t)))if(o=u[1]){if(9===m){if(!(a=e.getElementById(o)))return n;if(a.id===o)return y.call(n,a),n}else if(d&&(a=d.getElementById(o))&&J.contains(e,a)&&a.id===o)return y.call(n,a),n}else{if(u[2])return y.apply(n,e.getElementsByTagName(t)),n;if((o=u[3])&&e.getElementsByClassName)return y.apply(n,e.getElementsByClassName(o)),n}if(!(E[t+" "]||h&&h.test(t))){if(p=t,d=e,1===m&&(G.test(t)||U.test(t))){for((d=Y.test(t)&&st(e.parentNode)||e)==e&&v.scope||((s=e.getAttribute("id"))?s=k.escapeSelector(s):e.setAttribute("id",s=g)),i=(l=lt(t)).length;i--;)l[i]=(s?"#"+s:":scope")+" "+ft(l[i]);p=l.join(",")}try{return y.apply(n,d.querySelectorAll(p)),n}catch(e){E(t,!0)}finally{s===g&&e.removeAttribute("id")}}}return mt(t.replace(R,"$1"),e,n,r)}function tt(){var t=[];return function n(r,o){return t.push(r+" ")>e.cacheLength&&delete n[t.shift()],n[r+" "]=o}}function et(t){return t[g]=!0,t}function nt(t){var e=c.createElement("fieldset");try{return!!t(e)}catch(t){return!1}finally{e.parentNode&&e.parentNode.removeChild(e),e=null}}function rt(t){return function(e){return L(e,"input")&&e.type===t}}function ot(t){return function(e){return(L(e,"input")||L(e,"button"))&&e.type===t}}function it(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&Q(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function at(t){return et((function(e){return e=+e,et((function(n,r){for(var o,i=t([],n.length,e),a=i.length;a--;)n[o=i[a]]&&(n[o]=!(r[o]=n[o]))}))}))}function st(t){return t&&void 0!==t.getElementsByTagName&&t}function ct(t){var n,r=t?t.ownerDocument||t:D;return r!=c&&9===r.nodeType&&r.documentElement?(u=(c=r).documentElement,f=!k.isXMLDoc(c),d=u.matches||u.webkitMatchesSelector||u.msMatchesSelector,D!=c&&(n=c.defaultView)&&n.top!==n&&n.addEventListener("unload",X),v.getById=nt((function(t){return u.appendChild(t).id=k.expando,!c.getElementsByName||!c.getElementsByName(k.expando).length})),v.disconnectedMatch=nt((function(t){return d.call(t,"*")})),v.scope=nt((function(){return c.querySelectorAll(":scope")})),v.cssHas=nt((function(){try{return c.querySelector(":has(*,:jqfake)"),!1}catch(t){return!0}})),v.getById?(e.filter.ID=function(t){var e=t.replace(W,q);return function(t){return t.getAttribute("id")===e}},e.find.ID=function(t,e){if(void 0!==e.getElementById&&f){var n=e.getElementById(t);return n?[n]:[]}}):(e.filter.ID=function(t){var e=t.replace(W,q);return function(t){var n=void 0!==t.getAttributeNode&&t.getAttributeNode("id");return n&&n.value===e}},e.find.ID=function(t,e){if(void 0!==e.getElementById&&f){var n,r,o,i=e.getElementById(t);if(i){if((n=i.getAttributeNode("id"))&&n.value===t)return[i];for(o=e.getElementsByName(t),r=0;i=o[r++];)if((n=i.getAttributeNode("id"))&&n.value===t)return[i]}return[]}}),e.find.TAG=function(t,e){return void 0!==e.getElementsByTagName?e.getElementsByTagName(t):e.querySelectorAll(t)},e.find.CLASS=function(t,e){if(void 0!==e.getElementsByClassName&&f)return e.getElementsByClassName(t)},h=[],nt((function(t){var e;u.appendChild(t).innerHTML="",t.querySelectorAll("[selected]").length||h.push("\\["+O+"*(?:value|"+_+")"),t.querySelectorAll("[id~="+g+"-]").length||h.push("~="),t.querySelectorAll("a#"+g+"+*").length||h.push(".#.+[+~]"),t.querySelectorAll(":checked").length||h.push(":checked"),(e=c.createElement("input")).setAttribute("type","hidden"),t.appendChild(e).setAttribute("name","D"),u.appendChild(t).disabled=!0,2!==t.querySelectorAll(":disabled").length&&h.push(":enabled",":disabled"),(e=c.createElement("input")).setAttribute("name",""),t.appendChild(e),t.querySelectorAll("[name='']").length||h.push("\\["+O+"*name"+O+"*="+O+"*(?:''|\"\")")})),v.cssHas||h.push(":has"),h=h.length&&new RegExp(h.join("|")),C=function(t,e){if(t===e)return a=!0,0;var n=!t.compareDocumentPosition-!e.compareDocumentPosition;return n||(1&(n=(t.ownerDocument||t)==(e.ownerDocument||e)?t.compareDocumentPosition(e):1)||!v.sortDetached&&e.compareDocumentPosition(t)===n?t===c||t.ownerDocument==D&&J.contains(D,t)?-1:e===c||e.ownerDocument==D&&J.contains(D,e)?1:o?l.call(o,t)-l.call(o,e):0:4&n?-1:1)},c):c}for(t in J.matches=function(t,e){return J(t,null,null,e)},J.matchesSelector=function(t,e){if(ct(t),f&&!E[e+" "]&&(!h||!h.test(e)))try{var n=d.call(t,e);if(n||v.disconnectedMatch||t.document&&11!==t.document.nodeType)return n}catch(t){E(e,!0)}return J(e,c,null,[t]).length>0},J.contains=function(t,e){return(t.ownerDocument||t)!=c&&ct(t),k.contains(t,e)},J.attr=function(t,n){(t.ownerDocument||t)!=c&&ct(t);var r=e.attrHandle[n.toLowerCase()],o=r&&p.call(e.attrHandle,n.toLowerCase())?r(t,n,!f):void 0;return void 0!==o?o:t.getAttribute(n)},J.error=function(t){throw new Error("Syntax error, unrecognized expression: "+t)},k.uniqueSort=function(t){var e,n=[],r=0,i=0;if(a=!v.sortStable,o=!v.sortStable&&s.call(t,0),T.call(t,C),a){for(;e=t[i++];)e===t[i]&&(r=n.push(i));for(;r--;)P.call(t,n[r],1)}return o=null,t},k.fn.uniqueSort=function(){return this.pushStack(k.uniqueSort(s.apply(this)))},(e=k.expr={cacheLength:50,createPseudo:et,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){return t[1]=t[1].replace(W,q),t[3]=(t[3]||t[4]||t[5]||"").replace(W,q),"~="===t[2]&&(t[3]=" "+t[3]+" "),t.slice(0,4)},CHILD:function(t){return t[1]=t[1].toLowerCase(),"nth"===t[1].slice(0,3)?(t[3]||J.error(t[0]),t[4]=+(t[4]?t[5]+(t[6]||1):2*("even"===t[3]||"odd"===t[3])),t[5]=+(t[7]+t[8]||"odd"===t[3])):t[3]&&J.error(t[0]),t},PSEUDO:function(t){var e,n=!t[6]&&t[2];return V.CHILD.test(t[0])?null:(t[3]?t[2]=t[4]||t[5]||"":n&&H.test(n)&&(e=lt(n,!0))&&(e=n.indexOf(")",n.length-e)-n.length)&&(t[0]=t[0].slice(0,e),t[2]=n.slice(0,e)),t.slice(0,3))}},filter:{TAG:function(t){var e=t.replace(W,q).toLowerCase();return"*"===t?function(){return!0}:function(t){return L(t,e)}},CLASS:function(t){var e=w[t+" "];return e||(e=new RegExp("(^|"+O+")"+t+"("+O+"|$)"))&&w(t,(function(t){return e.test("string"==typeof t.className&&t.className||void 0!==t.getAttribute&&t.getAttribute("class")||"")}))},ATTR:function(t,e,n){return function(r){var o=J.attr(r,t);return null==o?"!="===e:!e||(o+="","="===e?o===n:"!="===e?o!==n:"^="===e?n&&0===o.indexOf(n):"*="===e?n&&o.indexOf(n)>-1:"$="===e?n&&o.slice(-n.length)===n:"~="===e?(" "+o.replace(F," ")+" ").indexOf(n)>-1:"|="===e&&(o===n||o.slice(0,n.length+1)===n+"-"))}},CHILD:function(t,e,n,r,o){var i="nth"!==t.slice(0,3),a="last"!==t.slice(-4),s="of-type"===e;return 1===r&&0===o?function(t){return!!t.parentNode}:function(e,n,c){var u,l,f,h,p,d=i!==a?"nextSibling":"previousSibling",y=e.parentNode,v=s&&e.nodeName.toLowerCase(),b=!c&&!s,w=!1;if(y){if(i){for(;d;){for(f=e;f=f[d];)if(s?L(f,v):1===f.nodeType)return!1;p=d="only"===t&&!p&&"nextSibling"}return!0}if(p=[a?y.firstChild:y.lastChild],a&&b){for(w=(h=(u=(l=y[g]||(y[g]={}))[t]||[])[0]===m&&u[1])&&u[2],f=h&&y.childNodes[h];f=++h&&f&&f[d]||(w=h=0)||p.pop();)if(1===f.nodeType&&++w&&f===e){l[t]=[m,h,w];break}}else if(b&&(w=h=(u=(l=e[g]||(e[g]={}))[t]||[])[0]===m&&u[1]),!1===w)for(;(f=++h&&f&&f[d]||(w=h=0)||p.pop())&&(!(s?L(f,v):1===f.nodeType)||!++w||(b&&((l=f[g]||(f[g]={}))[t]=[m,w]),f!==e)););return(w-=o)===r||w%r==0&&w/r>=0}}},PSEUDO:function(t,n){var r,o=e.pseudos[t]||e.setFilters[t.toLowerCase()]||J.error("unsupported pseudo: "+t);return o[g]?o(n):o.length>1?(r=[t,t,"",n],e.setFilters.hasOwnProperty(t.toLowerCase())?et((function(t,e){for(var r,i=o(t,n),a=i.length;a--;)t[r=l.call(t,i[a])]=!(e[r]=i[a])})):function(t){return o(t,0,r)}):o}},pseudos:{not:et((function(t){var e=[],n=[],r=gt(t.replace(R,"$1"));return r[g]?et((function(t,e,n,o){for(var i,a=r(t,null,o,[]),s=t.length;s--;)(i=a[s])&&(t[s]=!(e[s]=i))})):function(t,o,i){return e[0]=t,r(e,null,i,n),e[0]=null,!n.pop()}})),has:et((function(t){return function(e){return J(t,e).length>0}})),contains:et((function(t){return t=t.replace(W,q),function(e){return(e.textContent||k.text(e)).indexOf(t)>-1}})),lang:et((function(t){return $.test(t||"")||J.error("unsupported lang: "+t),t=t.replace(W,q).toLowerCase(),function(e){var n;do{if(n=f?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(n=n.toLowerCase())===t||0===n.indexOf(t+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}})),target:function(t){var e=r.location&&r.location.hash;return e&&e.slice(1)===t.id},root:function(t){return t===u},focus:function(t){return t===function(){try{return c.activeElement}catch(t){}}()&&c.hasFocus()&&!!(t.type||t.href||~t.tabIndex)},enabled:it(!1),disabled:it(!0),checked:function(t){return L(t,"input")&&!!t.checked||L(t,"option")&&!!t.selected},selected:function(t){return t.parentNode&&t.parentNode.selectedIndex,!0===t.selected},empty:function(t){for(t=t.firstChild;t;t=t.nextSibling)if(t.nodeType<6)return!1;return!0},parent:function(t){return!e.pseudos.empty(t)},header:function(t){return z.test(t.nodeName)},input:function(t){return Z.test(t.nodeName)},button:function(t){return L(t,"input")&&"button"===t.type||L(t,"button")},text:function(t){var e;return L(t,"input")&&"text"===t.type&&(null==(e=t.getAttribute("type"))||"text"===e.toLowerCase())},first:at((function(){return[0]})),last:at((function(t,e){return[e-1]})),eq:at((function(t,e,n){return[n<0?n+e:n]})),even:at((function(t,e){for(var n=0;ne?e:n;--r>=0;)t.push(r);return t})),gt:at((function(t,e,n){for(var r=n<0?n+e:n;++r1?function(e,n,r){for(var o=t.length;o--;)if(!t[o](e,n,r))return!1;return!0}:t[0]}function dt(t,e,n,r,o){for(var i,a=[],s=0,c=t.length,u=null!=e;s-1&&(i[u]=!(a[u]=h))}}else p=dt(p===a?p.splice(g,p.length):p),o?o(null,a,p,c):y.apply(a,p)}))}function vt(t){for(var r,o,i,a=t.length,s=e.relative[t[0].type],c=s||e.relative[" "],u=s?1:0,f=ht((function(t){return t===r}),c,!0),h=ht((function(t){return l.call(r,t)>-1}),c,!0),p=[function(t,e,o){var i=!s&&(o||e!=n)||((r=e).nodeType?f(t,e,o):h(t,e,o));return r=null,i}];u1&&pt(p),u>1&&ft(t.slice(0,u-1).concat({value:" "===t[u-2].type?"*":""})).replace(R,"$1"),o,u0,i=t.length>0,a=function(a,s,u,l,h){var p,d,v,g=0,b="0",w=a&&[],A=[],x=n,E=a||i&&e.find.TAG("*",h),C=m+=null==x?1:Math.random()||.1,_=E.length;for(h&&(n=s==c||s||h);b!==_&&null!=(p=E[b]);b++){if(i&&p){for(d=0,s||p.ownerDocument==c||(ct(p),u=!f);v=t[d++];)if(v(p,s||c,u)){y.call(l,p);break}h&&(m=C)}o&&((p=!v&&p)&&g--,a&&w.push(p))}if(g+=b,o&&b!==g){for(d=0;v=r[d++];)v(w,A,s,u);if(a){if(g>0)for(;b--;)w[b]||A[b]||(A[b]=S.call(l));A=dt(A)}y.apply(l,A),h&&!a&&A.length>0&&g+r.length>1&&k.uniqueSort(l)}return h&&(m=C,n=x),w};return o?et(a):a}(a,i))).selector=t}return s}function mt(t,n,r,o){var i,a,s,c,u,l="function"==typeof t&&t,h=!o&<(t=l.selector||t);if(r=r||[],1===h.length){if((a=h[0]=h[0].slice(0)).length>2&&"ID"===(s=a[0]).type&&9===n.nodeType&&f&&e.relative[a[1].type]){if(!(n=(e.find.ID(s.matches[0].replace(W,q),n)||[])[0]))return r;l&&(n=n.parentNode),t=t.slice(a.shift().value.length)}for(i=V.needsContext.test(t)?0:a.length;i--&&(s=a[i],!e.relative[c=s.type]);)if((u=e.find[c])&&(o=u(s.matches[0].replace(W,q),Y.test(a[0].type)&&st(n.parentNode)||n))){if(a.splice(i,1),!(t=o.length&&ft(a)))return y.apply(r,o),r;break}}return(l||gt(t,h))(o,n,!f,r,!n||Y.test(t)&&st(n.parentNode)||n),r}ut.prototype=e.filters=e.pseudos,e.setFilters=new ut,v.sortStable=g.split("").sort(C).join("")===g,ct(),v.sortDetached=nt((function(t){return 1&t.compareDocumentPosition(c.createElement("fieldset"))})),k.find=J,k.expr[":"]=k.expr.pseudos,k.unique=k.uniqueSort,J.compile=gt,J.select=mt,J.setDocument=ct,J.escape=k.escapeSelector,J.getText=k.text,J.isXML=k.isXMLDoc,J.selectors=k.expr,J.support=k.support,J.uniqueSort=k.uniqueSort}();var N=function(t,e,n){for(var r=[],o=void 0!==n;(t=t[e])&&9!==t.nodeType;)if(1===t.nodeType){if(o&&k(t).is(n))break;r.push(t)}return r},F=function(t,e){for(var n=[];t;t=t.nextSibling)1===t.nodeType&&t!==e&&n.push(t);return n},M=k.expr.match.needsContext,U=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function G(t,e,n){return g(e)?k.grep(t,(function(t,r){return!!e.call(t,r,t)!==n})):e.nodeType?k.grep(t,(function(t){return t===e!==n})):"string"!=typeof e?k.grep(t,(function(t){return l.call(e,t)>-1!==n})):k.filter(e,t,n)}k.filter=function(t,e,n){var r=e[0];return n&&(t=":not("+t+")"),1===e.length&&1===r.nodeType?k.find.matchesSelector(r,t)?[r]:[]:k.find.matches(t,k.grep(e,(function(t){return 1===t.nodeType})))},k.fn.extend({find:function(t){var e,n,r=this.length,o=this;if("string"!=typeof t)return this.pushStack(k(t).filter((function(){for(e=0;e1?k.uniqueSort(n):n},filter:function(t){return this.pushStack(G(this,t||[],!1))},not:function(t){return this.pushStack(G(this,t||[],!0))},is:function(t){return!!G(this,"string"==typeof t&&M.test(t)?k(t):t||[],!1).length}});var H,$=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(k.fn.init=function(t,e,n){var r,o;if(!t)return this;if(n=n||H,"string"==typeof t){if(!(r="<"===t[0]&&">"===t[t.length-1]&&t.length>=3?[null,t,null]:$.exec(t))||!r[1]&&e)return!e||e.jquery?(e||n).find(t):this.constructor(e).find(t);if(r[1]){if(e=e instanceof k?e[0]:e,k.merge(this,k.parseHTML(r[1],e&&e.nodeType?e.ownerDocument||e:b,!0)),U.test(r[1])&&k.isPlainObject(e))for(r in e)g(this[r])?this[r](e[r]):this.attr(r,e[r]);return this}return(o=b.getElementById(r[2]))&&(this[0]=o,this.length=1),this}return t.nodeType?(this[0]=t,this.length=1,this):g(t)?void 0!==n.ready?n.ready(t):t(k):k.makeArray(t,this)}).prototype=k.fn,H=k(b);var V=/^(?:parents|prev(?:Until|All))/,Z={children:!0,contents:!0,next:!0,prev:!0};function z(t,e){for(;(t=t[e])&&1!==t.nodeType;);return t}k.fn.extend({has:function(t){var e=k(t,this),n=e.length;return this.filter((function(){for(var t=0;t-1:1===n.nodeType&&k.find.matchesSelector(n,t))){i.push(n);break}return this.pushStack(i.length>1?k.uniqueSort(i):i)},index:function(t){return t?"string"==typeof t?l.call(k(t),this[0]):l.call(this,t.jquery?t[0]:t):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(t,e){return this.pushStack(k.uniqueSort(k.merge(this.get(),k(t,e))))},addBack:function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}}),k.each({parent:function(t){var e=t.parentNode;return e&&11!==e.nodeType?e:null},parents:function(t){return N(t,"parentNode")},parentsUntil:function(t,e,n){return N(t,"parentNode",n)},next:function(t){return z(t,"nextSibling")},prev:function(t){return z(t,"previousSibling")},nextAll:function(t){return N(t,"nextSibling")},prevAll:function(t){return N(t,"previousSibling")},nextUntil:function(t,e,n){return N(t,"nextSibling",n)},prevUntil:function(t,e,n){return N(t,"previousSibling",n)},siblings:function(t){return F((t.parentNode||{}).firstChild,t)},children:function(t){return F(t.firstChild)},contents:function(t){return null!=t.contentDocument&&a(t.contentDocument)?t.contentDocument:(L(t,"template")&&(t=t.content||t),k.merge([],t.childNodes))}},(function(t,e){k.fn[t]=function(n,r){var o=k.map(this,e,n);return"Until"!==t.slice(-5)&&(r=n),r&&"string"==typeof r&&(o=k.filter(r,o)),this.length>1&&(Z[t]||k.uniqueSort(o),V.test(t)&&o.reverse()),this.pushStack(o)}}));var K=/[^\x20\t\r\n\f]+/g;function Y(t){return t}function W(t){throw t}function q(t,e,n,r){var o;try{t&&g(o=t.promise)?o.call(t).done(e).fail(n):t&&g(o=t.then)?o.call(t,e,n):e.apply(void 0,[t].slice(r))}catch(t){n.apply(void 0,[t])}}k.Callbacks=function(t){t="string"==typeof t?function(t){var e={};return k.each(t.match(K)||[],(function(t,n){e[n]=!0})),e}(t):k.extend({},t);var e,n,r,o,i=[],a=[],s=-1,c=function(){for(o=o||t.once,r=e=!0;a.length;s=-1)for(n=a.shift();++s-1;)i.splice(n,1),n<=s&&s--})),this},has:function(t){return t?k.inArray(t,i)>-1:i.length>0},empty:function(){return i&&(i=[]),this},disable:function(){return o=a=[],i=n="",this},disabled:function(){return!i},lock:function(){return o=a=[],n||e||(i=n=""),this},locked:function(){return!!o},fireWith:function(t,n){return o||(n=[t,(n=n||[]).slice?n.slice():n],a.push(n),e||c()),this},fire:function(){return u.fireWith(this,arguments),this},fired:function(){return!!r}};return u},k.extend({Deferred:function(t){var e=[["notify","progress",k.Callbacks("memory"),k.Callbacks("memory"),2],["resolve","done",k.Callbacks("once memory"),k.Callbacks("once memory"),0,"resolved"],["reject","fail",k.Callbacks("once memory"),k.Callbacks("once memory"),1,"rejected"]],n="pending",o={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},catch:function(t){return o.then(null,t)},pipe:function(){var t=arguments;return k.Deferred((function(n){k.each(e,(function(e,r){var o=g(t[r[4]])&&t[r[4]];i[r[1]]((function(){var t=o&&o.apply(this,arguments);t&&g(t.promise)?t.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[r[0]+"With"](this,o?[t]:arguments)}))})),t=null})).promise()},then:function(t,n,o){var i=0;function a(t,e,n,o){return function(){var s=this,c=arguments,u=function(){var r,u;if(!(t=i&&(n!==W&&(s=void 0,c=[r]),e.rejectWith(s,c))}};t?l():(k.Deferred.getErrorHook?l.error=k.Deferred.getErrorHook():k.Deferred.getStackHook&&(l.error=k.Deferred.getStackHook()),r.setTimeout(l))}}return k.Deferred((function(r){e[0][3].add(a(0,r,g(o)?o:Y,r.notifyWith)),e[1][3].add(a(0,r,g(t)?t:Y)),e[2][3].add(a(0,r,g(n)?n:W))})).promise()},promise:function(t){return null!=t?k.extend(t,o):o}},i={};return k.each(e,(function(t,r){var a=r[2],s=r[5];o[r[1]]=a.add,s&&a.add((function(){n=s}),e[3-t][2].disable,e[3-t][3].disable,e[0][2].lock,e[0][3].lock),a.add(r[3].fire),i[r[0]]=function(){return i[r[0]+"With"](this===i?void 0:this,arguments),this},i[r[0]+"With"]=a.fireWith})),o.promise(i),t&&t.call(i,i),i},when:function(t){var e=arguments.length,n=e,r=Array(n),o=s.call(arguments),i=k.Deferred(),a=function(t){return function(n){r[t]=this,o[t]=arguments.length>1?s.call(arguments):n,--e||i.resolveWith(r,o)}};if(e<=1&&(q(t,i.done(a(n)).resolve,i.reject,!e),"pending"===i.state()||g(o[n]&&o[n].then)))return i.then();for(;n--;)q(o[n],a(n),i.reject);return i.promise()}});var X=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;k.Deferred.exceptionHook=function(t,e){r.console&&r.console.warn&&t&&X.test(t.name)&&r.console.warn("jQuery.Deferred exception: "+t.message,t.stack,e)},k.readyException=function(t){r.setTimeout((function(){throw t}))};var Q=k.Deferred();function J(){b.removeEventListener("DOMContentLoaded",J),r.removeEventListener("load",J),k.ready()}k.fn.ready=function(t){return Q.then(t).catch((function(t){k.readyException(t)})),this},k.extend({isReady:!1,readyWait:1,ready:function(t){(!0===t?--k.readyWait:k.isReady)||(k.isReady=!0,!0!==t&&--k.readyWait>0||Q.resolveWith(b,[k]))}}),k.ready.then=Q.then,"complete"===b.readyState||"loading"!==b.readyState&&!b.documentElement.doScroll?r.setTimeout(k.ready):(b.addEventListener("DOMContentLoaded",J),r.addEventListener("load",J));var tt=function(t,e,n,r,o,i,a){var s=0,c=t.length,u=null==n;if("object"===x(n))for(s in o=!0,n)tt(t,e,s,n[s],!0,i,a);else if(void 0!==r&&(o=!0,g(r)||(a=!0),u&&(a?(e.call(t,r),e=null):(u=e,e=function(t,e,n){return u.call(k(t),n)})),e))for(;s1,null,!0)},removeData:function(t){return this.each((function(){ct.remove(this,t)}))}}),k.extend({queue:function(t,e,n){var r;if(t)return e=(e||"fx")+"queue",r=st.get(t,e),n&&(!r||Array.isArray(n)?r=st.access(t,e,k.makeArray(n)):r.push(n)),r||[]},dequeue:function(t,e){e=e||"fx";var n=k.queue(t,e),r=n.length,o=n.shift(),i=k._queueHooks(t,e);"inprogress"===o&&(o=n.shift(),r--),o&&("fx"===e&&n.unshift("inprogress"),delete i.stop,o.call(t,(function(){k.dequeue(t,e)}),i)),!r&&i&&i.empty.fire()},_queueHooks:function(t,e){var n=e+"queueHooks";return st.get(t,n)||st.access(t,n,{empty:k.Callbacks("once memory").add((function(){st.remove(t,[e+"queue",n])}))})}}),k.fn.extend({queue:function(t,e){var n=2;return"string"!=typeof t&&(e=t,t="fx",n--),arguments.length\x20\t\r\n\f]*)/i,Lt=/^$|^module$|\/(?:java|ecma)script/i;Et=b.createDocumentFragment().appendChild(b.createElement("div")),(Ct=b.createElement("input")).setAttribute("type","radio"),Ct.setAttribute("checked","checked"),Ct.setAttribute("name","t"),Et.appendChild(Ct),v.checkClone=Et.cloneNode(!0).cloneNode(!0).lastChild.checked,Et.innerHTML="",v.noCloneChecked=!!Et.cloneNode(!0).lastChild.defaultValue,Et.innerHTML="",v.option=!!Et.lastChild;var St={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function Tt(t,e){var n;return n=void 0!==t.getElementsByTagName?t.getElementsByTagName(e||"*"):void 0!==t.querySelectorAll?t.querySelectorAll(e||"*"):[],void 0===e||e&&L(t,e)?k.merge([t],n):n}function Pt(t,e){for(var n=0,r=t.length;n",""]);var Ot=/<|&#?\w+;/;function Rt(t,e,n,r,o){for(var i,a,s,c,u,l,f=e.createDocumentFragment(),h=[],p=0,d=t.length;p-1)o&&o.push(i);else if(u=vt(i),a=Tt(f.appendChild(i),"script"),u&&Pt(a),n)for(l=0;i=a[l++];)Lt.test(i.type||"")&&n.push(i);return f}var It=/^([^.]*)(?:\.(.+)|)/;function jt(){return!0}function Dt(){return!1}function Bt(t,e,n,r,o,i){var a,s;if("object"==typeof e){for(s in"string"!=typeof n&&(r=r||n,n=void 0),e)Bt(t,s,n,r,e[s],i);return t}if(null==r&&null==o?(o=n,r=n=void 0):null==o&&("string"==typeof n?(o=r,r=void 0):(o=r,r=n,n=void 0)),!1===o)o=Dt;else if(!o)return t;return 1===i&&(a=o,(o=function(t){return k().off(t),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),t.each((function(){k.event.add(this,e,o,r,n)}))}function Nt(t,e,n){n?(st.set(t,e,!1),k.event.add(t,e,{namespace:!1,handler:function(t){var n,r=st.get(this,e);if(1&t.isTrigger&&this[e]){if(r)(k.event.special[e]||{}).delegateType&&t.stopPropagation();else if(r=s.call(arguments),st.set(this,e,r),this[e](),n=st.get(this,e),st.set(this,e,!1),r!==n)return t.stopImmediatePropagation(),t.preventDefault(),n}else r&&(st.set(this,e,k.event.trigger(r[0],r.slice(1),this)),t.stopPropagation(),t.isImmediatePropagationStopped=jt)}})):void 0===st.get(t,e)&&k.event.add(t,e,jt)}k.event={global:{},add:function(t,e,n,r,o){var i,a,s,c,u,l,f,h,p,d,y,v=st.get(t);if(it(t))for(n.handler&&(n=(i=n).handler,o=i.selector),o&&k.find.matchesSelector(yt,o),n.guid||(n.guid=k.guid++),(c=v.events)||(c=v.events=Object.create(null)),(a=v.handle)||(a=v.handle=function(e){return void 0!==k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),u=(e=(e||"").match(K)||[""]).length;u--;)p=y=(s=It.exec(e[u])||[])[1],d=(s[2]||"").split(".").sort(),p&&(f=k.event.special[p]||{},p=(o?f.delegateType:f.bindType)||p,f=k.event.special[p]||{},l=k.extend({type:p,origType:y,data:r,handler:n,guid:n.guid,selector:o,needsContext:o&&k.expr.match.needsContext.test(o),namespace:d.join(".")},i),(h=c[p])||((h=c[p]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,d,a)||t.addEventListener&&t.addEventListener(p,a)),f.add&&(f.add.call(t,l),l.handler.guid||(l.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,l):h.push(l),k.event.global[p]=!0)},remove:function(t,e,n,r,o){var i,a,s,c,u,l,f,h,p,d,y,v=st.hasData(t)&&st.get(t);if(v&&(c=v.events)){for(u=(e=(e||"").match(K)||[""]).length;u--;)if(p=y=(s=It.exec(e[u])||[])[1],d=(s[2]||"").split(".").sort(),p){for(f=k.event.special[p]||{},h=c[p=(r?f.delegateType:f.bindType)||p]||[],s=s[2]&&new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=i=h.length;i--;)l=h[i],!o&&y!==l.origType||n&&n.guid!==l.guid||s&&!s.test(l.namespace)||r&&r!==l.selector&&("**"!==r||!l.selector)||(h.splice(i,1),l.selector&&h.delegateCount--,f.remove&&f.remove.call(t,l));a&&!h.length&&(f.teardown&&!1!==f.teardown.call(t,d,v.handle)||k.removeEvent(t,p,v.handle),delete c[p])}else for(p in c)k.event.remove(t,p+e[u],n,r,!0);k.isEmptyObject(c)&&st.remove(t,"handle events")}},dispatch:function(t){var e,n,r,o,i,a,s=new Array(arguments.length),c=k.event.fix(t),u=(st.get(this,"events")||Object.create(null))[c.type]||[],l=k.event.special[c.type]||{};for(s[0]=c,e=1;e=1))for(;u!==this;u=u.parentNode||this)if(1===u.nodeType&&("click"!==t.type||!0!==u.disabled)){for(i=[],a={},n=0;n-1:k.find(o,this,null,[u]).length),a[o]&&i.push(r);i.length&&s.push({elem:u,handlers:i})}return u=this,c\s*$/g;function Gt(t,e){return L(t,"table")&&L(11!==e.nodeType?e:e.firstChild,"tr")&&k(t).children("tbody")[0]||t}function Ht(t){return t.type=(null!==t.getAttribute("type"))+"/"+t.type,t}function $t(t){return"true/"===(t.type||"").slice(0,5)?t.type=t.type.slice(5):t.removeAttribute("type"),t}function Vt(t,e){var n,r,o,i,a,s;if(1===e.nodeType){if(st.hasData(t)&&(s=st.get(t).events))for(o in st.remove(e,"handle events"),s)for(n=0,r=s[o].length;n1&&"string"==typeof d&&!v.checkClone&&Mt.test(d))return t.each((function(o){var i=t.eq(o);y&&(e[0]=d.call(this,o,i.html())),zt(i,e,n,r)}));if(h&&(i=(o=Rt(e,t[0].ownerDocument,!1,t,r)).firstChild,1===o.childNodes.length&&(o=i),i||r)){for(s=(a=k.map(Tt(o,"script"),Ht)).length;f0&&Pt(a,!c&&Tt(t,"script")),s},cleanData:function(t){for(var e,n,r,o=k.event.special,i=0;void 0!==(n=t[i]);i++)if(it(n)){if(e=n[st.expando]){if(e.events)for(r in e.events)o[r]?k.event.remove(n,r):k.removeEvent(n,r,e.handle);n[st.expando]=void 0}n[ct.expando]&&(n[ct.expando]=void 0)}}}),k.fn.extend({detach:function(t){return Kt(this,t,!0)},remove:function(t){return Kt(this,t)},text:function(t){return tt(this,(function(t){return void 0===t?k.text(this):this.empty().each((function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=t)}))}),null,t,arguments.length)},append:function(){return zt(this,arguments,(function(t){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Gt(this,t).appendChild(t)}))},prepend:function(){return zt(this,arguments,(function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=Gt(this,t);e.insertBefore(t,e.firstChild)}}))},before:function(){return zt(this,arguments,(function(t){this.parentNode&&this.parentNode.insertBefore(t,this)}))},after:function(){return zt(this,arguments,(function(t){this.parentNode&&this.parentNode.insertBefore(t,this.nextSibling)}))},empty:function(){for(var t,e=0;null!=(t=this[e]);e++)1===t.nodeType&&(k.cleanData(Tt(t,!1)),t.textContent="");return this},clone:function(t,e){return t=null!=t&&t,e=null==e?t:e,this.map((function(){return k.clone(this,t,e)}))},html:function(t){return tt(this,(function(t){var e=this[0]||{},n=0,r=this.length;if(void 0===t&&1===e.nodeType)return e.innerHTML;if("string"==typeof t&&!Ft.test(t)&&!St[(_t.exec(t)||["",""])[1].toLowerCase()]){t=k.htmlPrefilter(t);try{for(;n=0&&(c+=Math.max(0,Math.ceil(t["offset"+e[0].toUpperCase()+e.slice(1)]-i-c-s-.5))||0),c+u}function le(t,e,n){var r=qt(t),o=(!v.boxSizingReliable()||n)&&"border-box"===k.css(t,"boxSizing",!1,r),i=o,a=Jt(t,e,r),s="offset"+e[0].toUpperCase()+e.slice(1);if(Yt.test(a)){if(!n)return a;a="auto"}return(!v.boxSizingReliable()&&o||!v.reliableTrDimensions()&&L(t,"tr")||"auto"===a||!parseFloat(a)&&"inline"===k.css(t,"display",!1,r))&&t.getClientRects().length&&(o="border-box"===k.css(t,"boxSizing",!1,r),(i=s in t)&&(a=t[s])),(a=parseFloat(a)||0)+ue(t,e,n||(o?"border":"content"),i,r,a)+"px"}function fe(t,e,n,r,o){return new fe.prototype.init(t,e,n,r,o)}k.extend({cssHooks:{opacity:{get:function(t,e){if(e){var n=Jt(t,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,aspectRatio:!0,borderImageSlice:!0,columnCount:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,scale:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeMiterlimit:!0,strokeOpacity:!0},cssProps:{},style:function(t,e,n,r){if(t&&3!==t.nodeType&&8!==t.nodeType&&t.style){var o,i,a,s=ot(e),c=Wt.test(e),u=t.style;if(c||(e=oe(s)),a=k.cssHooks[e]||k.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(o=a.get(t,!1,r))?o:u[e];"string"==(i=typeof n)&&(o=pt.exec(n))&&o[1]&&(n=bt(t,e,o),i="number"),null!=n&&n==n&&("number"!==i||c||(n+=o&&o[3]||(k.cssNumber[s]?"":"px")),v.clearCloneStyle||""!==n||0!==e.indexOf("background")||(u[e]="inherit"),a&&"set"in a&&void 0===(n=a.set(t,n,r))||(c?u.setProperty(e,n):u[e]=n))}},css:function(t,e,n,r){var o,i,a,s=ot(e);return Wt.test(e)||(e=oe(s)),(a=k.cssHooks[e]||k.cssHooks[s])&&"get"in a&&(o=a.get(t,!0,n)),void 0===o&&(o=Jt(t,e,r)),"normal"===o&&e in se&&(o=se[e]),""===n||n?(i=parseFloat(o),!0===n||isFinite(i)?i||0:o):o}}),k.each(["height","width"],(function(t,e){k.cssHooks[e]={get:function(t,n,r){if(n)return!ie.test(k.css(t,"display"))||t.getClientRects().length&&t.getBoundingClientRect().width?le(t,e,r):Xt(t,ae,(function(){return le(t,e,r)}))},set:function(t,n,r){var o,i=qt(t),a=!v.scrollboxSize()&&"absolute"===i.position,s=(a||r)&&"border-box"===k.css(t,"boxSizing",!1,i),c=r?ue(t,e,r,s,i):0;return s&&a&&(c-=Math.ceil(t["offset"+e[0].toUpperCase()+e.slice(1)]-parseFloat(i[e])-ue(t,e,"border",!1,i)-.5)),c&&(o=pt.exec(n))&&"px"!==(o[3]||"px")&&(t.style[e]=n,n=k.css(t,e)),ce(0,n,c)}}})),k.cssHooks.marginLeft=te(v.reliableMarginLeft,(function(t,e){if(e)return(parseFloat(Jt(t,"marginLeft"))||t.getBoundingClientRect().left-Xt(t,{marginLeft:0},(function(){return t.getBoundingClientRect().left})))+"px"})),k.each({margin:"",padding:"",border:"Width"},(function(t,e){k.cssHooks[t+e]={expand:function(n){for(var r=0,o={},i="string"==typeof n?n.split(" "):[n];r<4;r++)o[t+dt[r]+e]=i[r]||i[r-2]||i[0];return o}},"margin"!==t&&(k.cssHooks[t+e].set=ce)})),k.fn.extend({css:function(t,e){return tt(this,(function(t,e,n){var r,o,i={},a=0;if(Array.isArray(e)){for(r=qt(t),o=e.length;a1)}}),k.Tween=fe,fe.prototype={constructor:fe,init:function(t,e,n,r,o,i){this.elem=t,this.prop=n,this.easing=o||k.easing._default,this.options=e,this.start=this.now=this.cur(),this.end=r,this.unit=i||(k.cssNumber[n]?"":"px")},cur:function(){var t=fe.propHooks[this.prop];return t&&t.get?t.get(this):fe.propHooks._default.get(this)},run:function(t){var e,n=fe.propHooks[this.prop];return this.options.duration?this.pos=e=k.easing[this.easing](t,this.options.duration*t,0,1,this.options.duration):this.pos=e=t,this.now=(this.end-this.start)*e+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):fe.propHooks._default.set(this),this}},fe.prototype.init.prototype=fe.prototype,fe.propHooks={_default:{get:function(t){var e;return 1!==t.elem.nodeType||null!=t.elem[t.prop]&&null==t.elem.style[t.prop]?t.elem[t.prop]:(e=k.css(t.elem,t.prop,""))&&"auto"!==e?e:0},set:function(t){k.fx.step[t.prop]?k.fx.step[t.prop](t):1!==t.elem.nodeType||!k.cssHooks[t.prop]&&null==t.elem.style[oe(t.prop)]?t.elem[t.prop]=t.now:k.style(t.elem,t.prop,t.now+t.unit)}}},fe.propHooks.scrollTop=fe.propHooks.scrollLeft={set:function(t){t.elem.nodeType&&t.elem.parentNode&&(t.elem[t.prop]=t.now)}},k.easing={linear:function(t){return t},swing:function(t){return.5-Math.cos(t*Math.PI)/2},_default:"swing"},k.fx=fe.prototype.init,k.fx.step={};var he,pe,de=/^(?:toggle|show|hide)$/,ye=/queueHooks$/;function ve(){pe&&(!1===b.hidden&&r.requestAnimationFrame?r.requestAnimationFrame(ve):r.setTimeout(ve,k.fx.interval),k.fx.tick())}function ge(){return r.setTimeout((function(){he=void 0})),he=Date.now()}function me(t,e){var n,r=0,o={height:t};for(e=e?1:0;r<4;r+=2-e)o["margin"+(n=dt[r])]=o["padding"+n]=t;return e&&(o.opacity=o.width=t),o}function be(t,e,n){for(var r,o=(we.tweeners[e]||[]).concat(we.tweeners["*"]),i=0,a=o.length;i1)},removeAttr:function(t){return this.each((function(){k.removeAttr(this,t)}))}}),k.extend({attr:function(t,e,n){var r,o,i=t.nodeType;if(3!==i&&8!==i&&2!==i)return void 0===t.getAttribute?k.prop(t,e,n):(1===i&&k.isXMLDoc(t)||(o=k.attrHooks[e.toLowerCase()]||(k.expr.match.bool.test(e)?Ae:void 0)),void 0!==n?null===n?void k.removeAttr(t,e):o&&"set"in o&&void 0!==(r=o.set(t,n,e))?r:(t.setAttribute(e,n+""),n):o&&"get"in o&&null!==(r=o.get(t,e))?r:null==(r=k.find.attr(t,e))?void 0:r)},attrHooks:{type:{set:function(t,e){if(!v.radioValue&&"radio"===e&&L(t,"input")){var n=t.value;return t.setAttribute("type",e),n&&(t.value=n),e}}}},removeAttr:function(t,e){var n,r=0,o=e&&e.match(K);if(o&&1===t.nodeType)for(;n=o[r++];)t.removeAttribute(n)}}),Ae={set:function(t,e,n){return!1===e?k.removeAttr(t,n):t.setAttribute(n,n),n}},k.each(k.expr.match.bool.source.match(/\w+/g),(function(t,e){var n=xe[e]||k.find.attr;xe[e]=function(t,e,r){var o,i,a=e.toLowerCase();return r||(i=xe[a],xe[a]=o,o=null!=n(t,e,r)?a:null,xe[a]=i),o}}));var Ee=/^(?:input|select|textarea|button)$/i,Ce=/^(?:a|area)$/i;function ke(t){return(t.match(K)||[]).join(" ")}function _e(t){return t.getAttribute&&t.getAttribute("class")||""}function Le(t){return Array.isArray(t)?t:"string"==typeof t&&t.match(K)||[]}k.fn.extend({prop:function(t,e){return tt(this,k.prop,t,e,arguments.length>1)},removeProp:function(t){return this.each((function(){delete this[k.propFix[t]||t]}))}}),k.extend({prop:function(t,e,n){var r,o,i=t.nodeType;if(3!==i&&8!==i&&2!==i)return 1===i&&k.isXMLDoc(t)||(e=k.propFix[e]||e,o=k.propHooks[e]),void 0!==n?o&&"set"in o&&void 0!==(r=o.set(t,n,e))?r:t[e]=n:o&&"get"in o&&null!==(r=o.get(t,e))?r:t[e]},propHooks:{tabIndex:{get:function(t){var e=k.find.attr(t,"tabindex");return e?parseInt(e,10):Ee.test(t.nodeName)||Ce.test(t.nodeName)&&t.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),v.optSelected||(k.propHooks.selected={get:function(t){var e=t.parentNode;return e&&e.parentNode&&e.parentNode.selectedIndex,null},set:function(t){var e=t.parentNode;e&&(e.selectedIndex,e.parentNode&&e.parentNode.selectedIndex)}}),k.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],(function(){k.propFix[this.toLowerCase()]=this})),k.fn.extend({addClass:function(t){var e,n,r,o,i,a;return g(t)?this.each((function(e){k(this).addClass(t.call(this,e,_e(this)))})):(e=Le(t)).length?this.each((function(){if(r=_e(this),n=1===this.nodeType&&" "+ke(r)+" "){for(i=0;i-1;)n=n.replace(" "+o+" "," ");a=ke(n),r!==a&&this.setAttribute("class",a)}})):this:this.attr("class","")},toggleClass:function(t,e){var n,r,o,i,a=typeof t,s="string"===a||Array.isArray(t);return g(t)?this.each((function(n){k(this).toggleClass(t.call(this,n,_e(this),e),e)})):"boolean"==typeof e&&s?e?this.addClass(t):this.removeClass(t):(n=Le(t),this.each((function(){if(s)for(i=k(this),o=0;o-1)return!0;return!1}});var Se=/\r/g;k.fn.extend({val:function(t){var e,n,r,o=this[0];return arguments.length?(r=g(t),this.each((function(n){var o;1===this.nodeType&&(null==(o=r?t.call(this,n,k(this).val()):t)?o="":"number"==typeof o?o+="":Array.isArray(o)&&(o=k.map(o,(function(t){return null==t?"":t+""}))),(e=k.valHooks[this.type]||k.valHooks[this.nodeName.toLowerCase()])&&"set"in e&&void 0!==e.set(this,o,"value")||(this.value=o))}))):o?(e=k.valHooks[o.type]||k.valHooks[o.nodeName.toLowerCase()])&&"get"in e&&void 0!==(n=e.get(o,"value"))?n:"string"==typeof(n=o.value)?n.replace(Se,""):null==n?"":n:void 0}}),k.extend({valHooks:{option:{get:function(t){var e=k.find.attr(t,"value");return null!=e?e:ke(k.text(t))}},select:{get:function(t){var e,n,r,o=t.options,i=t.selectedIndex,a="select-one"===t.type,s=a?null:[],c=a?i+1:o.length;for(r=i<0?c:a?i:0;r-1)&&(n=!0);return n||(t.selectedIndex=-1),i}}}}),k.each(["radio","checkbox"],(function(){k.valHooks[this]={set:function(t,e){if(Array.isArray(e))return t.checked=k.inArray(k(t).val(),e)>-1}},v.checkOn||(k.valHooks[this].get=function(t){return null===t.getAttribute("value")?"on":t.value})}));var Te=r.location,Pe={guid:Date.now()},Oe=/\?/;k.parseXML=function(t){var e,n;if(!t||"string"!=typeof t)return null;try{e=(new r.DOMParser).parseFromString(t,"text/xml")}catch(t){}return n=e&&e.getElementsByTagName("parsererror")[0],e&&!n||k.error("Invalid XML: "+(n?k.map(n.childNodes,(function(t){return t.textContent})).join("\n"):t)),e};var Re=/^(?:focusinfocus|focusoutblur)$/,Ie=function(t){t.stopPropagation()};k.extend(k.event,{trigger:function(t,e,n,o){var i,a,s,c,u,l,f,h,d=[n||b],y=p.call(t,"type")?t.type:t,v=p.call(t,"namespace")?t.namespace.split("."):[];if(a=h=s=n=n||b,3!==n.nodeType&&8!==n.nodeType&&!Re.test(y+k.event.triggered)&&(y.indexOf(".")>-1&&(v=y.split("."),y=v.shift(),v.sort()),u=y.indexOf(":")<0&&"on"+y,(t=t[k.expando]?t:new k.Event(y,"object"==typeof t&&t)).isTrigger=o?2:3,t.namespace=v.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+v.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=n),e=null==e?[t]:k.makeArray(e,[t]),f=k.event.special[y]||{},o||!f.trigger||!1!==f.trigger.apply(n,e))){if(!o&&!f.noBubble&&!m(n)){for(c=f.delegateType||y,Re.test(c+y)||(a=a.parentNode);a;a=a.parentNode)d.push(a),s=a;s===(n.ownerDocument||b)&&d.push(s.defaultView||s.parentWindow||r)}for(i=0;(a=d[i++])&&!t.isPropagationStopped();)h=a,t.type=i>1?c:f.bindType||y,(l=(st.get(a,"events")||Object.create(null))[t.type]&&st.get(a,"handle"))&&l.apply(a,e),(l=u&&a[u])&&l.apply&&it(a)&&(t.result=l.apply(a,e),!1===t.result&&t.preventDefault());return t.type=y,o||t.isDefaultPrevented()||f._default&&!1!==f._default.apply(d.pop(),e)||!it(n)||u&&g(n[y])&&!m(n)&&((s=n[u])&&(n[u]=null),k.event.triggered=y,t.isPropagationStopped()&&h.addEventListener(y,Ie),n[y](),t.isPropagationStopped()&&h.removeEventListener(y,Ie),k.event.triggered=void 0,s&&(n[u]=s)),t.result}},simulate:function(t,e,n){var r=k.extend(new k.Event,n,{type:t,isSimulated:!0});k.event.trigger(r,null,e)}}),k.fn.extend({trigger:function(t,e){return this.each((function(){k.event.trigger(t,e,this)}))},triggerHandler:function(t,e){var n=this[0];if(n)return k.event.trigger(t,e,n,!0)}});var je=/\[\]$/,De=/\r?\n/g,Be=/^(?:submit|button|image|reset|file)$/i,Ne=/^(?:input|select|textarea|keygen)/i;function Fe(t,e,n,r){var o;if(Array.isArray(e))k.each(e,(function(e,o){n||je.test(t)?r(t,o):Fe(t+"["+("object"==typeof o&&null!=o?e:"")+"]",o,n,r)}));else if(n||"object"!==x(e))r(t,e);else for(o in e)Fe(t+"["+o+"]",e[o],n,r)}k.param=function(t,e){var n,r=[],o=function(t,e){var n=g(e)?e():e;r[r.length]=encodeURIComponent(t)+"="+encodeURIComponent(null==n?"":n)};if(null==t)return"";if(Array.isArray(t)||t.jquery&&!k.isPlainObject(t))k.each(t,(function(){o(this.name,this.value)}));else for(n in t)Fe(n,t[n],e,o);return r.join("&")},k.fn.extend({serialize:function(){return k.param(this.serializeArray())},serializeArray:function(){return this.map((function(){var t=k.prop(this,"elements");return t?k.makeArray(t):this})).filter((function(){var t=this.type;return this.name&&!k(this).is(":disabled")&&Ne.test(this.nodeName)&&!Be.test(t)&&(this.checked||!kt.test(t))})).map((function(t,e){var n=k(this).val();return null==n?null:Array.isArray(n)?k.map(n,(function(t){return{name:e.name,value:t.replace(De,"\r\n")}})):{name:e.name,value:n.replace(De,"\r\n")}})).get()}});var Me=/%20/g,Ue=/#.*$/,Ge=/([?&])_=[^&]*/,He=/^(.*?):[ \t]*([^\r\n]*)$/gm,$e=/^(?:GET|HEAD)$/,Ve=/^\/\//,Ze={},ze={},Ke="*/".concat("*"),Ye=b.createElement("a");function We(t){return function(e,n){"string"!=typeof e&&(n=e,e="*");var r,o=0,i=e.toLowerCase().match(K)||[];if(g(n))for(;r=i[o++];)"+"===r[0]?(r=r.slice(1)||"*",(t[r]=t[r]||[]).unshift(n)):(t[r]=t[r]||[]).push(n)}}function qe(t,e,n,r){var o={},i=t===ze;function a(s){var c;return o[s]=!0,k.each(t[s]||[],(function(t,s){var u=s(e,n,r);return"string"!=typeof u||i||o[u]?i?!(c=u):void 0:(e.dataTypes.unshift(u),a(u),!1)})),c}return a(e.dataTypes[0])||!o["*"]&&a("*")}function Xe(t,e){var n,r,o=k.ajaxSettings.flatOptions||{};for(n in e)void 0!==e[n]&&((o[n]?t:r||(r={}))[n]=e[n]);return r&&k.extend(!0,t,r),t}Ye.href=Te.href,k.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Te.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Te.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Ke,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":k.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(t,e){return e?Xe(Xe(t,k.ajaxSettings),e):Xe(k.ajaxSettings,t)},ajaxPrefilter:We(Ze),ajaxTransport:We(ze),ajax:function(t,e){"object"==typeof t&&(e=t,t=void 0),e=e||{};var n,o,i,a,s,c,u,l,f,h,p=k.ajaxSetup({},e),d=p.context||p,y=p.context&&(d.nodeType||d.jquery)?k(d):k.event,v=k.Deferred(),g=k.Callbacks("once memory"),m=p.statusCode||{},w={},A={},x="canceled",E={readyState:0,getResponseHeader:function(t){var e;if(u){if(!a)for(a={};e=He.exec(i);)a[e[1].toLowerCase()+" "]=(a[e[1].toLowerCase()+" "]||[]).concat(e[2]);e=a[t.toLowerCase()+" "]}return null==e?null:e.join(", ")},getAllResponseHeaders:function(){return u?i:null},setRequestHeader:function(t,e){return null==u&&(t=A[t.toLowerCase()]=A[t.toLowerCase()]||t,w[t]=e),this},overrideMimeType:function(t){return null==u&&(p.mimeType=t),this},statusCode:function(t){var e;if(t)if(u)E.always(t[E.status]);else for(e in t)m[e]=[m[e],t[e]];return this},abort:function(t){var e=t||x;return n&&n.abort(e),C(0,e),this}};if(v.promise(E),p.url=((t||p.url||Te.href)+"").replace(Ve,Te.protocol+"//"),p.type=e.method||e.type||p.method||p.type,p.dataTypes=(p.dataType||"*").toLowerCase().match(K)||[""],null==p.crossDomain){c=b.createElement("a");try{c.href=p.url,c.href=c.href,p.crossDomain=Ye.protocol+"//"+Ye.host!=c.protocol+"//"+c.host}catch(t){p.crossDomain=!0}}if(p.data&&p.processData&&"string"!=typeof p.data&&(p.data=k.param(p.data,p.traditional)),qe(Ze,p,e,E),u)return E;for(f in(l=k.event&&p.global)&&0==k.active++&&k.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!$e.test(p.type),o=p.url.replace(Ue,""),p.hasContent?p.data&&p.processData&&0===(p.contentType||"").indexOf("application/x-www-form-urlencoded")&&(p.data=p.data.replace(Me,"+")):(h=p.url.slice(o.length),p.data&&(p.processData||"string"==typeof p.data)&&(o+=(Oe.test(o)?"&":"?")+p.data,delete p.data),!1===p.cache&&(o=o.replace(Ge,"$1"),h=(Oe.test(o)?"&":"?")+"_="+Pe.guid+++h),p.url=o+h),p.ifModified&&(k.lastModified[o]&&E.setRequestHeader("If-Modified-Since",k.lastModified[o]),k.etag[o]&&E.setRequestHeader("If-None-Match",k.etag[o])),(p.data&&p.hasContent&&!1!==p.contentType||e.contentType)&&E.setRequestHeader("Content-Type",p.contentType),E.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Ke+"; q=0.01":""):p.accepts["*"]),p.headers)E.setRequestHeader(f,p.headers[f]);if(p.beforeSend&&(!1===p.beforeSend.call(d,E,p)||u))return E.abort();if(x="abort",g.add(p.complete),E.done(p.success),E.fail(p.error),n=qe(ze,p,e,E)){if(E.readyState=1,l&&y.trigger("ajaxSend",[E,p]),u)return E;p.async&&p.timeout>0&&(s=r.setTimeout((function(){E.abort("timeout")}),p.timeout));try{u=!1,n.send(w,C)}catch(t){if(u)throw t;C(-1,t)}}else C(-1,"No Transport");function C(t,e,a,c){var f,h,b,w,A,x=e;u||(u=!0,s&&r.clearTimeout(s),n=void 0,i=c||"",E.readyState=t>0?4:0,f=t>=200&&t<300||304===t,a&&(w=function(t,e,n){for(var r,o,i,a,s=t.contents,c=t.dataTypes;"*"===c[0];)c.shift(),void 0===r&&(r=t.mimeType||e.getResponseHeader("Content-Type"));if(r)for(o in s)if(s[o]&&s[o].test(r)){c.unshift(o);break}if(c[0]in n)i=c[0];else{for(o in n){if(!c[0]||t.converters[o+" "+c[0]]){i=o;break}a||(a=o)}i=i||a}if(i)return i!==c[0]&&c.unshift(i),n[i]}(p,E,a)),!f&&k.inArray("script",p.dataTypes)>-1&&k.inArray("json",p.dataTypes)<0&&(p.converters["text script"]=function(){}),w=function(t,e,n,r){var o,i,a,s,c,u={},l=t.dataTypes.slice();if(l[1])for(a in t.converters)u[a.toLowerCase()]=t.converters[a];for(i=l.shift();i;)if(t.responseFields[i]&&(n[t.responseFields[i]]=e),!c&&r&&t.dataFilter&&(e=t.dataFilter(e,t.dataType)),c=i,i=l.shift())if("*"===i)i=c;else if("*"!==c&&c!==i){if(!(a=u[c+" "+i]||u["* "+i]))for(o in u)if((s=o.split(" "))[1]===i&&(a=u[c+" "+s[0]]||u["* "+s[0]])){!0===a?a=u[o]:!0!==u[o]&&(i=s[0],l.unshift(s[1]));break}if(!0!==a)if(a&&t.throws)e=a(e);else try{e=a(e)}catch(t){return{state:"parsererror",error:a?t:"No conversion from "+c+" to "+i}}}return{state:"success",data:e}}(p,w,E,f),f?(p.ifModified&&((A=E.getResponseHeader("Last-Modified"))&&(k.lastModified[o]=A),(A=E.getResponseHeader("etag"))&&(k.etag[o]=A)),204===t||"HEAD"===p.type?x="nocontent":304===t?x="notmodified":(x=w.state,h=w.data,f=!(b=w.error))):(b=x,!t&&x||(x="error",t<0&&(t=0))),E.status=t,E.statusText=(e||x)+"",f?v.resolveWith(d,[h,x,E]):v.rejectWith(d,[E,x,b]),E.statusCode(m),m=void 0,l&&y.trigger(f?"ajaxSuccess":"ajaxError",[E,p,f?h:b]),g.fireWith(d,[E,x]),l&&(y.trigger("ajaxComplete",[E,p]),--k.active||k.event.trigger("ajaxStop")))}return E},getJSON:function(t,e,n){return k.get(t,e,n,"json")},getScript:function(t,e){return k.get(t,void 0,e,"script")}}),k.each(["get","post"],(function(t,e){k[e]=function(t,n,r,o){return g(n)&&(o=o||r,r=n,n=void 0),k.ajax(k.extend({url:t,type:e,dataType:o,data:n,success:r},k.isPlainObject(t)&&t))}})),k.ajaxPrefilter((function(t){var e;for(e in t.headers)"content-type"===e.toLowerCase()&&(t.contentType=t.headers[e]||"")})),k._evalUrl=function(t,e,n){return k.ajax({url:t,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(t){k.globalEval(t,e,n)}})},k.fn.extend({wrapAll:function(t){var e;return this[0]&&(g(t)&&(t=t.call(this[0])),e=k(t,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&e.insertBefore(this[0]),e.map((function(){for(var t=this;t.firstElementChild;)t=t.firstElementChild;return t})).append(this)),this},wrapInner:function(t){return g(t)?this.each((function(e){k(this).wrapInner(t.call(this,e))})):this.each((function(){var e=k(this),n=e.contents();n.length?n.wrapAll(t):e.append(t)}))},wrap:function(t){var e=g(t);return this.each((function(n){k(this).wrapAll(e?t.call(this,n):t)}))},unwrap:function(t){return this.parent(t).not("body").each((function(){k(this).replaceWith(this.childNodes)})),this}}),k.expr.pseudos.hidden=function(t){return!k.expr.pseudos.visible(t)},k.expr.pseudos.visible=function(t){return!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)},k.ajaxSettings.xhr=function(){try{return new r.XMLHttpRequest}catch(t){}};var Qe={0:200,1223:204},Je=k.ajaxSettings.xhr();v.cors=!!Je&&"withCredentials"in Je,v.ajax=Je=!!Je,k.ajaxTransport((function(t){var e,n;if(v.cors||Je&&!t.crossDomain)return{send:function(o,i){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];for(a in t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||o["X-Requested-With"]||(o["X-Requested-With"]="XMLHttpRequest"),o)s.setRequestHeader(a,o[a]);e=function(t){return function(){e&&(e=n=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===t?s.abort():"error"===t?"number"!=typeof s.status?i(0,"error"):i(s.status,s.statusText):i(Qe[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=e(),n=s.onerror=s.ontimeout=e("error"),void 0!==s.onabort?s.onabort=n:s.onreadystatechange=function(){4===s.readyState&&r.setTimeout((function(){e&&n()}))},e=e("abort");try{s.send(t.hasContent&&t.data||null)}catch(t){if(e)throw t}},abort:function(){e&&e()}}})),k.ajaxPrefilter((function(t){t.crossDomain&&(t.contents.script=!1)})),k.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(t){return k.globalEval(t),t}}}),k.ajaxPrefilter("script",(function(t){void 0===t.cache&&(t.cache=!1),t.crossDomain&&(t.type="GET")})),k.ajaxTransport("script",(function(t){var e,n;if(t.crossDomain||t.scriptAttrs)return{send:function(r,o){e=k(" -``` - -## Documentation - -See our [full documentation](https://cookieconsent.osano.com/documentation/). - -## Contributing - -Feel free to improve the plugin and send us a pull request. - -The easiest way to develop is to host the files with a local webserver. e.g. - -```sh -python -m SimpleHTTPServer -``` - -We use Gulp to compile the SCSS and minify the JavaScript. You can run a build with: - -```sh -gulp build -``` - -## License - -Code released under the [MIT licence](http://opensource.org/licenses/MIT). - -## Credits - -Cookie Consent v3 - -- Alex Morley-Finch (@alexmorleyfinch) - JavaScript -- Piiu Pilt - JavaScript -- Oliver Emberton (@oliveremberton) - a couple of lines of CSS, maybe - -Cookie Consent v2 - -- David Ball (@drball) - CSS / themes -- Adam Hutchinson (@adjohu) - JavaScript diff --git a/node_modules/cookieconsent/bower.json b/node_modules/cookieconsent/bower.json deleted file mode 100644 index 7b2426ddf..000000000 --- a/node_modules/cookieconsent/bower.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "cookieconsent", - "version": "3.1.1", - "homepage": "http://cookieconsent.osano.com/", - "authors": ["Osano"], - "description": "Osano cookie consent plugin", - "main": ["build/cookieconsent.min.js", "build/cookieconsent.min.css"], - "keywords": ["cookieconsent", "cookie", "law"], - "license": "MIT", - "ignore": ["**/.*", "node_modules", "bower_components", "test", "tests"] -} diff --git a/node_modules/cookieconsent/build/cookieconsent.min.css b/node_modules/cookieconsent/build/cookieconsent.min.css deleted file mode 100644 index d4d439025..000000000 --- a/node_modules/cookieconsent/build/cookieconsent.min.css +++ /dev/null @@ -1,6 +0,0 @@ -.cc-window{opacity:1;-webkit-transition:opacity 1s ease;transition:opacity 1s ease}.cc-window.cc-invisible{opacity:0}.cc-animate.cc-revoke{-webkit-transition:transform 1s ease;-webkit-transition:-webkit-transform 1s ease;transition:-webkit-transform 1s ease;transition:transform 1s ease;transition:transform 1s ease,-webkit-transform 1s ease}.cc-animate.cc-revoke.cc-top{-webkit-transform:translateY(-2em);transform:translateY(-2em)}.cc-animate.cc-revoke.cc-bottom{-webkit-transform:translateY(2em);transform:translateY(2em)}.cc-animate.cc-revoke.cc-active.cc-top{-webkit-transform:translateY(0);transform:translateY(0)}.cc-animate.cc-revoke.cc-active.cc-bottom{-webkit-transform:translateY(0);transform:translateY(0)}.cc-revoke:hover{-webkit-transform:translateY(0);transform:translateY(0)}.cc-grower{max-height:0;overflow:hidden;-webkit-transition:max-height 1s;transition:max-height 1s} -.cc-revoke,.cc-window{position:fixed;overflow:hidden;-webkit-box-sizing:border-box;box-sizing:border-box;font-family:Helvetica,Calibri,Arial,sans-serif;font-size:16px;line-height:1.5em;display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:nowrap;flex-wrap:nowrap;z-index:9999}.cc-window.cc-static{position:static}.cc-window.cc-floating{padding:2em;max-width:24em;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.cc-window.cc-banner{padding:1em 1.8em;width:100%;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.cc-revoke{padding:.5em}.cc-revoke:hover{text-decoration:underline}.cc-header{font-size:18px;font-weight:700}.cc-btn,.cc-close,.cc-link,.cc-revoke{cursor:pointer}.cc-link{opacity:.8;display:inline-block;padding:.2em;text-decoration:underline}.cc-link:hover{opacity:1}.cc-link:active,.cc-link:visited{color:initial}.cc-btn{display:block;padding:.4em .8em;font-size:.9em;font-weight:700;border-width:2px;border-style:solid;text-align:center;white-space:nowrap}.cc-highlight .cc-btn:first-child{background-color:transparent;border-color:transparent}.cc-highlight .cc-btn:first-child:focus,.cc-highlight .cc-btn:first-child:hover{background-color:transparent;text-decoration:underline}.cc-close{display:block;position:absolute;top:.5em;right:.5em;font-size:1.6em;opacity:.9;line-height:.75}.cc-close:focus,.cc-close:hover{opacity:1} -.cc-revoke.cc-top{top:0;left:3em;border-bottom-left-radius:.5em;border-bottom-right-radius:.5em}.cc-revoke.cc-bottom{bottom:0;left:3em;border-top-left-radius:.5em;border-top-right-radius:.5em}.cc-revoke.cc-left{left:3em;right:unset}.cc-revoke.cc-right{right:3em;left:unset}.cc-top{top:1em}.cc-left{left:1em}.cc-right{right:1em}.cc-bottom{bottom:1em}.cc-floating>.cc-link{margin-bottom:1em}.cc-floating .cc-message{display:block;margin-bottom:1em}.cc-window.cc-floating .cc-compliance{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto}.cc-window.cc-banner{-webkit-box-align:center;-ms-flex-align:center;align-items:center}.cc-banner.cc-top{left:0;right:0;top:0}.cc-banner.cc-bottom{left:0;right:0;bottom:0}.cc-banner .cc-message{display:block;-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto;max-width:100%;margin-right:1em}.cc-compliance{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-ms-flex-line-pack:justify;align-content:space-between}.cc-floating .cc-compliance>.cc-btn{-webkit-box-flex:1;-ms-flex:1;flex:1}.cc-btn+.cc-btn{margin-left:.5em} -@media print{.cc-revoke,.cc-window{display:none}}@media screen and (max-width:900px){.cc-btn{white-space:normal}}@media screen and (max-width:414px) and (orientation:portrait),screen and (max-width:736px) and (orientation:landscape){.cc-window.cc-top{top:0}.cc-window.cc-bottom{bottom:0}.cc-window.cc-banner,.cc-window.cc-floating,.cc-window.cc-left,.cc-window.cc-right{left:0;right:0}.cc-window.cc-banner{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.cc-window.cc-banner .cc-compliance{-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto}.cc-window.cc-floating{max-width:none}.cc-window .cc-message{margin-bottom:1em}.cc-window.cc-banner{-webkit-box-align:unset;-ms-flex-align:unset;align-items:unset}.cc-window.cc-banner .cc-message{margin-right:0}} -.cc-floating.cc-theme-classic{padding:1.2em;border-radius:5px}.cc-floating.cc-type-info.cc-theme-classic .cc-compliance{text-align:center;display:inline;-webkit-box-flex:0;-ms-flex:none;flex:none}.cc-theme-classic .cc-btn{border-radius:5px}.cc-theme-classic .cc-btn:last-child{min-width:140px}.cc-floating.cc-type-info.cc-theme-classic .cc-btn{display:inline-block} -.cc-theme-edgeless.cc-window{padding:0}.cc-floating.cc-theme-edgeless .cc-message{margin:2em;margin-bottom:1.5em}.cc-banner.cc-theme-edgeless .cc-btn{margin:0;padding:.8em 1.8em;height:100%}.cc-banner.cc-theme-edgeless .cc-message{margin-left:1em}.cc-floating.cc-theme-edgeless .cc-btn+.cc-btn{margin-left:0} \ No newline at end of file diff --git a/node_modules/cookieconsent/build/cookieconsent.min.js b/node_modules/cookieconsent/build/cookieconsent.min.js deleted file mode 100644 index 1e3dccf1a..000000000 --- a/node_modules/cookieconsent/build/cookieconsent.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e){if(!e.hasInitialised){var t={escapeRegExp:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},hasClass:function(e,t){var i=" ";return 1===e.nodeType&&(i+e.className+i).replace(/[\n\t]/g,i).indexOf(i+t+i)>=0},addClass:function(e,t){e.className+=" "+t},removeClass:function(e,t){var i=new RegExp("\\b"+this.escapeRegExp(t)+"\\b");e.className=e.className.replace(i,"")},interpolateString:function(e,t){return e.replace(/{{([a-z][a-z0-9\-_]*)}}/gi,function(e){return t(arguments[1])||""})},getCookie:function(e){var t=("; "+document.cookie).split("; "+e+"=");return t.length<2?void 0:t.pop().split(";").shift()},setCookie:function(e,t,i,n,o,s){var r=new Date;r.setHours(r.getHours()+24*(i||365));var a=[e+"="+t,"expires="+r.toUTCString(),"path="+(o||"/")];n&&a.push("domain="+n),s&&a.push("secure"),document.cookie=a.join(";")},deepExtend:function(e,t){for(var i in t)t.hasOwnProperty(i)&&(i in e&&this.isPlainObject(e[i])&&this.isPlainObject(t[i])?this.deepExtend(e[i],t[i]):e[i]=t[i]);return e},throttle:function(e,t){var i=!1;return function(){i||(e.apply(this,arguments),i=!0,setTimeout(function(){i=!1},t))}},hash:function(e){var t,i,n=0;if(0===e.length)return n;for(t=0,i=e.length;t=128?"#000":"#fff"},getLuminance:function(e){var t=parseInt(this.normaliseHex(e),16),i=38+(t>>16),n=38+(t>>8&255),o=38+(255&t);return"#"+(16777216+65536*(i<255?i<1?0:i:255)+256*(n<255?n<1?0:n:255)+(o<255?o<1?0:o:255)).toString(16).slice(1)},isMobile:function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)},isPlainObject:function(e){return"object"==typeof e&&null!==e&&e.constructor==Object},traverseDOMPath:function(e,i){return e&&e.parentNode?t.hasClass(e,i)?e:this.traverseDOMPath(e.parentNode,i):null}};e.status={deny:"deny",allow:"allow",dismiss:"dismiss"},e.transitionEnd=function(){var e=document.createElement("div"),t={t:"transitionend",OT:"oTransitionEnd",msT:"MSTransitionEnd",MozT:"transitionend",WebkitT:"webkitTransitionEnd"};for(var i in t)if(t.hasOwnProperty(i)&&void 0!==e.style[i+"ransition"])return t[i];return""}(),e.hasTransition=!!e.transitionEnd;var i=Object.keys(e.status).map(t.escapeRegExp);e.customStyles={},e.Popup=function(){var n={enabled:!0,container:null,cookie:{name:"cookieconsent_status",path:"/",domain:"",expiryDays:365,secure:!1},onPopupOpen:function(){},onPopupClose:function(){},onInitialise:function(e){},onStatusChange:function(e,t){},onRevokeChoice:function(){},onNoCookieLaw:function(e,t){},content:{header:"Cookies used on the website!",message:"This website uses cookies to ensure you get the best experience on our website.",dismiss:"Got it!",allow:"Allow cookies",deny:"Decline",link:"Learn more",href:"https://www.cookiesandyou.com",close:"❌",target:"_blank",policy:"Cookie Policy"},elements:{header:'{{header}} ',message:'{{message}}',messagelink:'{{message}} {{link}}',dismiss:'{{dismiss}}',allow:'{{allow}}',deny:'{{deny}}',link:'{{link}}',close:'{{close}}'},window:'',revokeBtn:'
{{policy}}
',compliance:{info:'
{{dismiss}}
',"opt-in":'
{{deny}}{{allow}}
',"opt-out":'
{{deny}}{{allow}}
'},type:"info",layouts:{basic:"{{messagelink}}{{compliance}}","basic-close":"{{messagelink}}{{compliance}}{{close}}","basic-header":"{{header}}{{message}}{{link}}{{compliance}}"},layout:"basic",position:"bottom",theme:"block",static:!1,palette:null,revokable:!1,animateRevokable:!0,showLink:!0,dismissOnScroll:!1,dismissOnTimeout:!1,dismissOnWindowClick:!1,ignoreClicksFrom:["cc-revoke","cc-btn"],autoOpen:!0,autoAttach:!0,whitelistPage:[],blacklistPage:[],overrideHTML:null};function o(){this.initialise.apply(this,arguments)}function s(e){this.openingTimeout=null,t.removeClass(e,"cc-invisible")}function r(t){t.style.display="none",t.removeEventListener(e.transitionEnd,this.afterTransition),this.afterTransition=null}function a(){var e=this.options.position.split("-"),t=[];return e.forEach(function(e){t.push("cc-"+e)}),t}function c(n){var o=this.options,s=document.createElement("div"),r=o.container&&1===o.container.nodeType?o.container:document.body;s.innerHTML=n;var a=s.children[0];return a.style.display="none",t.hasClass(a,"cc-window")&&e.hasTransition&&t.addClass(a,"cc-invisible"),this.onButtonClick=function(n){var o=t.traverseDOMPath(n.target,"cc-btn")||n.target;if(t.hasClass(o,"cc-btn")){var s=o.className.match(new RegExp("\\bcc-("+i.join("|")+")\\b")),r=s&&s[1]||!1;r&&(this.setStatus(r),this.close(!0))}t.hasClass(o,"cc-close")&&(this.setStatus(e.status.dismiss),this.close(!0));t.hasClass(o,"cc-revoke")&&this.revokeChoice()}.bind(this),a.addEventListener("click",this.onButtonClick),o.autoAttach&&(r.firstChild?r.insertBefore(a,r.firstChild):r.appendChild(a)),a}function l(e){return"000000"==(e=t.normaliseHex(e))?"#222":t.getLuminance(e)}function u(e,t){for(var i=0,n=e.length;i=0;o&&t(n);return o}.call(this)&&(this.options.enabled=!1),u(this.options.blacklistPage,location.pathname)&&(this.options.enabled=!1),u(this.options.whitelistPage,location.pathname)&&(this.options.enabled=!0);var o=this.options.window.replace("{{classes}}",function(){var i=this.options,n="top"==i.position||"bottom"==i.position?"banner":"floating";t.isMobile()&&(n="floating");var o=["cc-"+n,"cc-type-"+i.type,"cc-theme-"+i.theme];i.static&&o.push("cc-static");o.push.apply(o,a.call(this));(function(i){var n=t.hash(JSON.stringify(i)),o="cc-color-override-"+n,s=t.isPlainObject(i);this.customStyleSelector=s?o:null,s&&function(i,n,o){if(e.customStyles[i])return void++e.customStyles[i].references;var s={},r=n.popup,a=n.button,c=n.highlight;r&&(r.text=r.text?r.text:t.getContrast(r.background),r.link=r.link?r.link:r.text,s[o+".cc-window"]=["color: "+r.text,"background-color: "+r.background],s[o+".cc-revoke"]=["color: "+r.text,"background-color: "+r.background],s[o+" .cc-link,"+o+" .cc-link:active,"+o+" .cc-link:visited"]=["color: "+r.link],a&&(a.text=a.text?a.text:t.getContrast(a.background),a.border=a.border?a.border:"transparent",s[o+" .cc-btn"]=["color: "+a.text,"border-color: "+a.border,"background-color: "+a.background],a.padding&&s[o+" .cc-btn"].push("padding: "+a.padding),"transparent"!=a.background&&(s[o+" .cc-btn:hover, "+o+" .cc-btn:focus"]=["background-color: "+(a.hover||l(a.background))]),c?(c.text=c.text?c.text:t.getContrast(c.background),c.border=c.border?c.border:"transparent",s[o+" .cc-highlight .cc-btn:first-child"]=["color: "+c.text,"border-color: "+c.border,"background-color: "+c.background]):s[o+" .cc-highlight .cc-btn:first-child"]=["color: "+r.text]));var u=document.createElement("style");document.head.appendChild(u),e.customStyles[i]={references:1,element:u.sheet};var h=-1;for(var p in s)s.hasOwnProperty(p)&&u.sheet.insertRule(p+"{"+s[p].join(";")+"}",++h)}(n,i,"."+o);return s}).call(this,this.options.palette);this.customStyleSelector&&o.push(this.customStyleSelector);return o}.call(this).join(" ")).replace("{{children}}",function(){var e={},i=this.options;i.showLink||(i.elements.link="",i.elements.messagelink=i.elements.message);Object.keys(i.elements).forEach(function(n){e[n]=t.interpolateString(i.elements[n],function(e){var t=i.content[e];return e&&"string"==typeof t&&t.length?t:""})});var n=i.compliance[i.type];n||(n=i.compliance.info);e.compliance=t.interpolateString(n,function(t){return e[t]});var o=i.layouts[i.layout];o||(o=i.layouts.basic);return t.interpolateString(o,function(t){return e[t]})}.call(this)),s=this.options.overrideHTML;if("string"==typeof s&&s.length&&(o=s),this.options.static){var r=c.call(this,'
'+o+"
");r.style.display="",this.element=r.firstChild,this.element.style.display="none",t.addClass(this.element,"cc-invisible")}else this.element=c.call(this,o);(function(){var i=this.setStatus.bind(this),n=this.close.bind(this),o=this.options.dismissOnTimeout;"number"==typeof o&&o>=0&&(this.dismissTimeout=window.setTimeout(function(){i(e.status.dismiss),n(!0)},Math.floor(o)));var s=this.options.dismissOnScroll;if("number"==typeof s&&s>=0){var r=function(t){window.pageYOffset>Math.floor(s)&&(i(e.status.dismiss),n(!0),window.removeEventListener("scroll",r),this.onWindowScroll=null)};this.options.enabled&&(this.onWindowScroll=r,window.addEventListener("scroll",r))}var a=this.options.dismissOnWindowClick,c=this.options.ignoreClicksFrom;if(a){var l=function(o){for(var s=!1,r=o.path.length,a=c.length,u=0;uo&&(i=!0),i?t.hasClass(n,"cc-active")||t.addClass(n,"cc-active"):t.hasClass(n,"cc-active")&&t.removeClass(n,"cc-active")},200);this.onMouseMove=o,window.addEventListener("mousemove",o)}}}.call(this),this.options.autoOpen&&this.autoOpen()},o.prototype.destroy=function(){this.onButtonClick&&this.element&&(this.element.removeEventListener("click",this.onButtonClick),this.onButtonClick=null),this.dismissTimeout&&(clearTimeout(this.dismissTimeout),this.dismissTimeout=null),this.onWindowScroll&&(window.removeEventListener("scroll",this.onWindowScroll),this.onWindowScroll=null),this.onWindowClick&&(window.removeEventListener("click",this.onWindowClick),this.onWindowClick=null),this.onMouseMove&&(window.removeEventListener("mousemove",this.onMouseMove),this.onMouseMove=null),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.revokeBtn&&this.revokeBtn.parentNode&&this.revokeBtn.parentNode.removeChild(this.revokeBtn),this.revokeBtn=null,function(i){if(t.isPlainObject(i)){var n=t.hash(JSON.stringify(i)),o=e.customStyles[n];if(o&&!--o.references){var s=o.element.ownerNode;s&&s.parentNode&&s.parentNode.removeChild(s),e.customStyles[n]=null}}}(this.options.palette),this.options=null},o.prototype.open=function(t){if(this.element)return this.isOpen()||(e.hasTransition?this.fadeIn():this.element.style.display="",this.options.revokable&&this.toggleRevokeButton(),this.options.onPopupOpen.call(this)),this},o.prototype.close=function(t){if(this.element)return this.isOpen()&&(e.hasTransition?this.fadeOut():this.element.style.display="none",t&&this.options.revokable&&this.toggleRevokeButton(!0),this.options.onPopupClose.call(this)),this},o.prototype.fadeIn=function(){var i=this.element;if(e.hasTransition&&i&&(this.afterTransition&&r.call(this,i),t.hasClass(i,"cc-invisible"))){if(i.style.display="",this.options.static){var n=this.element.clientHeight;this.element.parentNode.style.maxHeight=n+"px"}this.openingTimeout=setTimeout(s.bind(this,i),20)}},o.prototype.fadeOut=function(){var i=this.element;e.hasTransition&&i&&(this.openingTimeout&&(clearTimeout(this.openingTimeout),s.bind(this,i)),t.hasClass(i,"cc-invisible")||(this.options.static&&(this.element.parentNode.style.maxHeight=""),this.afterTransition=r.bind(this,i),i.addEventListener(e.transitionEnd,this.afterTransition),t.addClass(i,"cc-invisible")))},o.prototype.isOpen=function(){return this.element&&""==this.element.style.display&&(!e.hasTransition||!t.hasClass(this.element,"cc-invisible"))},o.prototype.toggleRevokeButton=function(e){this.revokeBtn&&(this.revokeBtn.style.display=e?"":"none")},o.prototype.revokeChoice=function(e){this.options.enabled=!0,this.clearStatus(),this.options.onRevokeChoice.call(this),e||this.autoOpen()},o.prototype.hasAnswered=function(t){return Object.keys(e.status).indexOf(this.getStatus())>=0},o.prototype.hasConsented=function(t){var i=this.getStatus();return i==e.status.allow||i==e.status.dismiss},o.prototype.autoOpen=function(e){!this.hasAnswered()&&this.options.enabled?this.open():this.hasAnswered()&&this.options.revokable&&this.toggleRevokeButton(!0)},o.prototype.setStatus=function(i){var n=this.options.cookie,o=t.getCookie(n.name),s=Object.keys(e.status).indexOf(o)>=0;Object.keys(e.status).indexOf(i)>=0?(t.setCookie(n.name,i,n.expiryDays,n.domain,n.path,n.secure),this.options.onStatusChange.call(this,i,s)):this.clearStatus()},o.prototype.getStatus=function(){return t.getCookie(this.options.cookie.name)},o.prototype.clearStatus=function(){var e=this.options.cookie;t.setCookie(e.name,"",-1,e.domain,e.path)},o}(),e.Location=function(){var e={timeout:5e3,services:["ipinfo"],serviceDefinitions:{ipinfo:function(){return{url:"//ipinfo.io",headers:["Accept: application/json"],callback:function(e,t){try{var i=JSON.parse(t);return i.error?s(i):{code:i.country}}catch(e){return s({error:"Invalid response ("+e+")"})}}}},ipinfodb:function(e){return{url:"//api.ipinfodb.com/v3/ip-country/?key={api_key}&format=json&callback={callback}",isScript:!0,callback:function(e,t){try{var i=JSON.parse(t);return"ERROR"==i.statusCode?s({error:i.statusMessage}):{code:i.countryCode}}catch(e){return s({error:"Invalid response ("+e+")"})}}}},maxmind:function(){return{url:"//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js",isScript:!0,callback:function(e){window.geoip2?geoip2.country(function(t){try{e({code:t.country.iso_code})}catch(t){e(s(t))}},function(t){e(s(t))}):e(new Error("Unexpected response format. The downloaded script should have exported `geoip2` to the global scope"))}}}}};function i(i){t.deepExtend(this.options={},e),t.isPlainObject(i)&&t.deepExtend(this.options,i),this.currentServiceIndex=-1}function n(e,t,i){var n,o=document.createElement("script");o.type="text/"+(e.type||"javascript"),o.src=e.src||e,o.async=!1,o.onreadystatechange=o.onload=function(){var e=o.readyState;clearTimeout(n),t.done||e&&!/loaded|complete/.test(e)||(t.done=!0,t(),o.onreadystatechange=o.onload=null)},document.body.appendChild(o),n=setTimeout(function(){t.done=!0,t(),o.onreadystatechange=o.onload=null},i)}function o(e,t,i,n,o){var s=new(window.XMLHttpRequest||window.ActiveXObject)("MSXML2.XMLHTTP.3.0");if(s.open(n?"POST":"GET",e,1),s.setRequestHeader("Content-type","application/x-www-form-urlencoded"),Array.isArray(o))for(var r=0,a=o.length;r3&&t(s)}),s.send(n)}function s(e){return new Error("Error ["+(e.code||"UNKNOWN")+"]: "+e.error)}return i.prototype.getNextService=function(){var e;do{e=this.getServiceByIdx(++this.currentServiceIndex)}while(this.currentServiceIndex=0,revokable:t.revokable.indexOf(e)>=0,explicitAction:t.explicitAction.indexOf(e)>=0}},i.prototype.applyLaw=function(e,t){var i=this.get(t);return i.hasLaw||(e.enabled=!1,"function"==typeof e.onNoCookieLaw&&e.onNoCookieLaw(t,i)),this.options.regionalLaw&&(i.revokable&&(e.revokable=!0),i.explicitAction&&(e.dismissOnScroll=!1,e.dismissOnTimeout=!1)),e},i}(),e.initialise=function(i,n,o){var s=new e.Law(i.law);n||(n=function(){}),o||(o=function(){});var r=Object.keys(e.status),a=t.getCookie("cookieconsent_status");r.indexOf(a)>=0?n(new e.Popup(i)):e.getCountryCode(i,function(t){delete i.law,delete i.location,t.code&&(i=s.applyLaw(i,t.code)),n(new e.Popup(i))},function(t){delete i.law,delete i.location,o(t,new e.Popup(i))})},e.getCountryCode=function(t,i,n){t.law&&t.law.countryCode?i({code:t.law.countryCode}):t.location?new e.Location(t.location).locate(function(e){i(e||{})},n):i({})},e.utils=t,e.hasInitialised=!0,window.cookieconsent=e}}(window.cookieconsent||{}); \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/customTheme.css b/node_modules/cookieconsent/examples/customTheme.css deleted file mode 100644 index 7177bc4af..000000000 --- a/node_modules/cookieconsent/examples/customTheme.css +++ /dev/null @@ -1,72 +0,0 @@ -.cc-window { - color: black; -} - -.cc-banner .cc-message { - width: auto; - background: white; - padding: 20px 76px 20px 16px; - border-radius: 10px; - margin-right: -70px; - margin-left: 10%; -} - -.cc-link, -.cc-link:visited { - color: red; -} - -.cc-btn { - background: #0000ff; - background: -moz-radial-gradient( - center, - ellipse cover, - #0000ff 0%, - #99007c 100% - ); - background: -webkit-radial-gradient( - center, - ellipse cover, - #0000ff 0%, - #99007c 100% - ); - background: radial-gradient(ellipse at center, #0000ff 0%, #99007c 100%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#0000ff', endColorstr='#99007c',GradientType=1 ); - padding: 58px 0; - color: red; - border: 4px dotted red; - border-radius: 100px; - -webkit-animation: spin 4s linear infinite; - -moz-animation: spin 4s linear infinite; - animation: spin 4s linear infinite; - height: 150px; - width: 150px; - padding: 0; - line-height: 10; -} - -.cc-btn:hover { - background: #99007c; - -webkit-animation: none; - -moz-animation: none; - animation: none; -} - -@-moz-keyframes spin { - 100% { - -moz-transform: rotate(360deg); - } -} - -@-webkit-keyframes spin { - 100% { - -webkit-transform: rotate(360deg); - } -} - -@keyframes spin { - 100% { - -webkit-transform: rotate(360deg); - transform: rotate(360deg); - } -} diff --git a/node_modules/cookieconsent/examples/example-1-themes.html b/node_modules/cookieconsent/examples/example-1-themes.html deleted file mode 100644 index db68bb1b8..000000000 --- a/node_modules/cookieconsent/examples/example-1-themes.html +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - Demo 1 - Themes - - - - - - -
-
-
- -

- Demo 1 Themes

- -

- See what you can do with some of - Cookie Consent's themes: -

- -
    - - - -
    -
    -
    - - - - \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/example-2-custom-theme.html b/node_modules/cookieconsent/examples/example-2-custom-theme.html deleted file mode 100644 index 62cfd192a..000000000 --- a/node_modules/cookieconsent/examples/example-2-custom-theme.html +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - Demo 2 - Custom CSS - - - - - - - -
    -
    -
    - -

    - Demo 2 Custom CSS

    - -

    - See every part of - Cookie Consent overridden with slightly crazy custom CSS. -

    - -
      - - - - -
      -
      -
      - - - - \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/example-3-informational.html b/node_modules/cookieconsent/examples/example-3-informational.html deleted file mode 100644 index 4d084f34a..000000000 --- a/node_modules/cookieconsent/examples/example-3-informational.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - Demo 3 - Informational - - - - - - -
      -
      -
      - -

      - Demo 3 Informational

      - -

      - An - informational notice simply tells users that we use cookies, and lets the user dismiss the message. This - is the simplest solution, and recommended for most websites. -

      - -
        - - - - -
        -
        -
        - - - - \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/example-4-opt-out.html b/node_modules/cookieconsent/examples/example-4-opt-out.html deleted file mode 100644 index f3aaaa064..000000000 --- a/node_modules/cookieconsent/examples/example-4-opt-out.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - Demo 4 - Opt-out - - - - - - -
        -
        -
        -

        - Demo 4 Opt-out

        - -

        - An - opt-out notice tell users that we’re using cookies, and lets them choose if they wish to out-out of cookies - or not. If they opt-out, a small tab lets them change their mind later. -

        - -
          - - - - -
          -
          -
          - - - - \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/example-5-opt-in.html b/node_modules/cookieconsent/examples/example-5-opt-in.html deleted file mode 100644 index 69ea472ca..000000000 --- a/node_modules/cookieconsent/examples/example-5-opt-in.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - Demo 5 - Opt-in - - - - - - -
          -
          -
          -

          - Demo 5 Opt-in

          - -

          - An - opt-in notice ask users for permission to use cookies. Unless they say so, no cookies will be used. A small - tab allows them to change their mind later. -

          - -
            - - - - -
            -
            -
            - - - - \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/example-6-location.html b/node_modules/cookieconsent/examples/example-6-location.html deleted file mode 100644 index 95f06d242..000000000 --- a/node_modules/cookieconsent/examples/example-6-location.html +++ /dev/null @@ -1,334 +0,0 @@ - - - - - - - - - Demo 6 - Location - - - - - - - - -
            -
            -
            -

            - Demo 6 Location

            -

            - If you want, - Cookie Consent can automatically adapt to the user's location. Choose a country and see how the law and banner - changes: -

            - -
            - - -
            - -
            - - - - -
            -
            -
            - - - - \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/example-7-javascript-api.html b/node_modules/cookieconsent/examples/example-7-javascript-api.html deleted file mode 100644 index ec5beeeb6..000000000 --- a/node_modules/cookieconsent/examples/example-7-javascript-api.html +++ /dev/null @@ -1,140 +0,0 @@ - - - - - - - - - Demo 7 - JavaScript API - - - - - - -
            -
            -
            - -

            - Demo 7 JavaScript API

            - -

            - Programmers can hook into our - JavaScript API. Fire events to see what happens: -

            - -

            Popup

            - -
            - - - -
            - -

            Set status

            - -
            - - - - -
            - -

            Console

            - -
            
            -
            -          
            -
            -        
            -
            -
            - - - - \ No newline at end of file diff --git a/node_modules/cookieconsent/examples/script.js b/node_modules/cookieconsent/examples/script.js deleted file mode 100644 index 697b853ff..000000000 --- a/node_modules/cookieconsent/examples/script.js +++ /dev/null @@ -1,130 +0,0 @@ -window['cookieconsent_example_util'] = { - // Fill a select element with options (html can be configured using `cb`) - fillSelect: function(select, options, selected, cb) { - var html = ''; - if (typeof cb != 'function') { - cb = this.getSimpleOption; - } - for (var prop in options) { - html += cb(options[prop], prop, prop == selected); - } - select.innerHTML = html; - }, - - getSimpleOption: function(label, value, selected) { - return ( - '' - ); - }, - - tabularObject: function(obj, formatVal, formatKey) { - var html = '
              '; - var defaultFn = function() { - return arguments[0]; - }; - - if (typeof formatKey != 'function') formatKey = defaultFn; - if (typeof formatVal != 'function') formatVal = defaultFn; - - for (var prop in obj) { - html += - '
            • ' + - formatKey(prop, obj[prop]) + - ' ' + - formatVal(obj[prop], prop) + - '
            • '; - } - return html + '
            '; - }, - - initialisePopupSelector: function(options) { - var examples = Object.keys(options.popups); - var itemOpen = '
          • '; - var itemClose = '
          • '; - var instances = []; - - options.selector.innerHTML = - itemOpen + - Object.keys(options.popups).join(itemClose + itemOpen) + - itemClose; - - options.selector.onclick = function(e) { - var targ = e.target, - item; - - // if the target is the container, exit - if (targ.isEqualNode(options.selector)) return; - - // from this point, only the child elements of opts.selector will get through. - // out of these child elements, we want to find the closest direct decendant
          • - while (targ.tagName != 'LI' && targ.parentNode) { - targ = targ.parentNode; - } - - if (!targ.parentNode.isEqualNode(options.selector)) return; - - // from this point, 'targ' will be a direct decendant of opts.selector - var idx = Array.prototype.indexOf.call(options.selector.children, targ); - - if (idx >= 0 && instances[idx]) { - instances[idx].clearStatus(); - - // We could remember the popup that's currently open, but it gets complicated when we consider - // the revoke button. Therefore, simply close them all regardless - instances.forEach(function(popup) { - if (popup.isOpen()) { - popup.close(); - } - popup.toggleRevokeButton(false); - }); - - instances[idx].open(); - } - }; - - for (var i = 0, l = examples.length; i < l; ++i) { - options.popups[examples[i]].onPopupOpen = (function(options) { - return function() { - var codediv = document.getElementById('options'); - if (codediv) { - codediv.innerHTML = JSON.stringify(options, null, 2); - } - }; - })(options.popups[examples[i]]); - - var myOpts = options.popups[examples[i]]; - - myOpts.autoOpen = false; - - options.cookieconsent.initialise( - myOpts, - function(idx, popup) { - instances[idx] = popup; - }.bind(null, i), - function(idx, err, popup) { - instances[idx] = popup; - console.error(err); - }.bind(null, i) - ); - } - - return instances; - } -}; - -function timeStamp() { - var now = new Date(); - var time = [now.getHours(), now.getMinutes(), now.getSeconds()]; - for (var i = 1; i < 3; i++) { - if (time[i] < 10) { - time[i] = '0' + time[i]; - } - } - return '[' + time.join(':') + '] '; -} diff --git a/node_modules/cookieconsent/examples/style.css b/node_modules/cookieconsent/examples/style.css deleted file mode 100644 index b90d3c029..000000000 --- a/node_modules/cookieconsent/examples/style.css +++ /dev/null @@ -1,302 +0,0 @@ -body, -html { - margin: 0; - padding: 0; - font-family: 'proxima-nova', sans-serif; - font-size: 20px; - height: 100%; - background: #3f4f79; - background: radial-gradient(ellipse at center, #3f4f79 0%, #1d1d2b 100%); -} - -body.example2 { - background: #5f4f59; - background: radial-gradient(ellipse at center, #5f4f59 0%, #2d1d2b 100%); -} - -body.example3 { - background: #7f5f49; - background: radial-gradient(ellipse at center, #5f7f49 0%, #1d1d2b 100%); -} - -body.example4 { - background: #7f5f49; - background: radial-gradient(ellipse at center, #7f5f49 0%, #1d1d2b 100%); -} - -body.example5 { - background: #7f3f49; - background: radial-gradient(ellipse at center, #7f3f49 0%, #1d1d2b 100%); -} - -body.example6 { - background: #3f5f59; - background: radial-gradient(ellipse at center, #3f5f59 0%, #1d1d2b 100%); -} - -body.example7 { - background: #604060; - background: radial-gradient(ellipse at center, #604060 0%, #1d1d2b 100%); -} - -pre { - border-radius: 5px; - font-size: 12px; - line-height: 16px; - text-align: left; - background: black; - padding: 20px; - max-height: 300px; - width: 60%; - margin: 0 20% 30px 20%; - overflow: auto; -} - -pre .alert { - color: #d00; -} - -p a { - text-decoration: none; - border-bottom: 1px solid rgba(255, 255, 255, 0.3); -} - -p { - line-height: 1.4em; -} - -a, -a:visited { - color: #fff; -} - -em { - opacity: 0.7; - font-style: normal; -} - -h1 span { - font-weight: lighter; - opacity: 0.6; -} - -h3 { - opacity: 0.6; - font-weight: normal; -} - -/**************** Page switcher ****************/ - -.page-switcher { - background: rgba(0, 0, 0, 0.2); - color: rgba(255, 255, 255, 0.5); - text-decoration: none; - transition: all 0.25s; - position: fixed; - top: 50%; - height: 100px; - width: 100px; - margin-top: -50px; - font-size: 40px; - display: flex; - align-content: center; - align-items: center; - justify-content: center; -} - -.page-switcher:hover { - background: rgba(0, 0, 0, 0.4); -} - -.page-switcher-prev { - left: 0; -} - -.page-switcher-prev:hover { - left: -10px; -} - -.page-switcher-next { - right: 0; -} - -.page-switcher-next:hover { - right: -10px; -} - -/**************** JavaScript API examples ****************/ - -#console { - height: 100px; - width: 100%; - overflow-x: hidden; - overflow-y: scroll; - margin: 0 0 30px 0; -} - -/******************** Example window ********************/ - -.example-window { - text-align: center; - color: #e9e9e9; - max-width: 40em; - display: inline-block; -} - -.example-window h1 { - margin: 0 0 0.5em 0; -} - -.example-window p { - margin: 0 0 1em 0; -} - -.example-window button { - margin: 0; - padding: 0.5em; - font-size: 1em; -} - -/******************** Forms ********************/ - -.form-controls { - margin: 40px; -} - -.form-controls label { - display: block; - text-align: center; - opacity: 0.5; - margin-bottom: 10px; -} - -.btn-group { - margin-bottom: 10px; -} - -.btn, -.btn:visited { - display: inline-block; - background: #fff; - color: #000; - border: 0; - padding: 0.5em 1.4em; - text-decoration: none; - border-radius: 0.2em; - transition: all 0.25s; - margin: 0 0.25em; -} - -.btn:hover { - background: #ddd; - color: #000; -} - -/******************** Table ********************/ - -table th { - text-align: right; - font-weight: normal; - opacity: 0.5; -} - -/******************** Example selector ********************/ - -ul { - list-style: none; - padding: 0; -} - -.example-selector > li { - display: inline-block; - height: 6em; - width: 6em; - color: rgba(0, 0, 0, 0.7); - background: rgba(255, 255, 255, 0.7); - text-align: center; - cursor: pointer; - margin: 0.5em; - padding: 0.5em; - overflow: hidden; - transition: all 0.25s; - border-radius: 5px; -} - -.example-selector > li:hover { - color: rgba(0, 0, 0, 1); - background: rgba(255, 255, 255, 0.9); -} - -.example-selector > li:before { - content: ''; - display: inline-block; - vertical-align: middle; - height: 100%; -} - -.example-selector > li > span { - display: inline-block; - vertical-align: middle; - padding: 3px 5px; -} - -/******************** SelectBox ********************/ - -.selectbox { - text-align: center; - font-size: inherit; - max-width: 20em; - padding: 0.2em 0.4em; -} - -/******************** Layout ********************/ - -.center-outer { - display: table; -} - -.center-inner { - display: table-cell; - vertical-align: middle; - text-align: center; -} - -.fit { - width: 100%; - height: 100%; -} - -/******************** Code ********************/ - -#options { - display: none; -} - -/******************** Responsiveness ********************/ - -@media (min-width: 820px) and (max-width: 1000px) { - .example-window { - margin: 0 100px; - } -} - -@media (max-width: 819px) { - body { - padding: 20px; - } - - .example-window { - margin: 0; - } - - .page-switcher { - position: inherit; - display: inline-block; - padding: 10px 10px; - width: 30px; - height: 30px; - font-size: 20px; - border-radius: 50%; - margin: 20px 0; - } -} diff --git a/node_modules/cookieconsent/gulpfile.js b/node_modules/cookieconsent/gulpfile.js deleted file mode 100644 index b80c66b4e..000000000 --- a/node_modules/cookieconsent/gulpfile.js +++ /dev/null @@ -1,76 +0,0 @@ -const gulp = require('gulp'); -const concat = require('gulp-concat'); -const minifyJS = require('gulp-terser'); -const minifyCSS = require('gulp-clean-css'); -const deleteDirs = require('del'); -const autoprefixer = require('gulp-autoprefixer'); -const bump = require('gulp-bump'); -const yargs = require('yargs'); -const diff = require('gulp-diff-4'); - - -let buildFolder = './build'; -const jsBuildFiles = [ - './src/cookieconsent.js' -]; -const cssBuildFiles = [ - // defined explicitly so they are combined in order - './src/styles/animation.css', - './src/styles/base.css', - './src/styles/layout.css', - './src/styles/media.css', - - // all theme files - './src/styles/themes/*.css', -]; - - -gulp.task('cleanup:begin', function () { - return deleteDirs([buildFolder]); -}); - -gulp.task('minify:js', function () { - return gulp.src(jsBuildFiles) // get files - .pipe(minifyJS()) // minify them - .pipe(concat('cookieconsent.min.js')) // combine them - .pipe(gulp.dest(buildFolder)); // save under a new name -}); - -gulp.task('minify:css', function () { - return gulp.src(cssBuildFiles) // get files - .pipe(autoprefixer({browsers: ['IE 10', 'last 2 versions']})) - .pipe(minifyCSS()) // minify them - .pipe(concat('cookieconsent.min.css')) // combine them - .pipe(gulp.dest(buildFolder)); // save under a new name -}); - -gulp.task('bump', function() { - return gulp.src(['./bower.json', './package.json']) - .pipe(bump({'version': yargs.argv.tag})) - .pipe(gulp.dest('./')) -}); - -gulp.task('build', gulp.series('cleanup:begin', 'minify:js', 'minify:css')); - -gulp.task('verify', function() { - buildFolder = "./build-verify"; - return new Promise(gulp.series('cleanup:begin', 'minify:js', 'minify:css', 'verify:diff')); -}); - -gulp.task('verify:diff', function() { - return gulp.src('./build/*') - .pipe(diff('./build-verify')) - .pipe(diff.reporter({ fail: true })); -}); - -gulp.task('build:release', function() { - if (yargs.argv.tag===undefined) { - throw "A version number (e.g. 3.0.1) is required to build a release of cookieconsent" - } - - return new Promise(gulp.series('build', 'bump')); -}); - -gulp.task('watch', function() { - gulp.watch(cssBuildFiles.concat(jsBuildFiles), ['build']); -}); \ No newline at end of file diff --git a/node_modules/cookieconsent/licence b/node_modules/cookieconsent/licence deleted file mode 100644 index 1e1f1e043..000000000 --- a/node_modules/cookieconsent/licence +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Silktide Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/cookieconsent/package.json b/node_modules/cookieconsent/package.json deleted file mode 100644 index 320e60831..000000000 --- a/node_modules/cookieconsent/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "cookieconsent", - "version": "3.1.1", - "description": "Osano cookie consent tool.", - "main": "build/cookieconsent.min.js", - "devDependencies": { - "autoprefixer": "^9.5.1", - "del": "^4.1.1", - "gulp": "^4.0.2", - "gulp-autoprefixer": "^6.1.0", - "gulp-bump": "^2.4.0", - "gulp-clean-css": "^4.2.0", - "gulp-cli": "^2.2.0", - "gulp-concat": "^2.6.1", - "gulp-diff-4": "^4.0.1", - "gulp-terser": "^1.2.0", - "yargs": "^13.2.4" - }, - "homepage": "http://cookieconsent.osano.com/", - "scripts": { - "build": "gulp build", - "verify": "gulp verify", - "build:release": "gulp build:release --tag $npm_package_version", - "test": "echo \"Error: no test specified\" && exit 0" - }, - "repository": { - "type": "git", - "url": "https://github.com/osano/cookieconsent.git" - }, - "author": "Osano, Inc., a Public Benefit Corporation", - "license": "MIT" -} diff --git a/node_modules/cookieconsent/src/cookieconsent.js b/node_modules/cookieconsent/src/cookieconsent.js deleted file mode 100644 index c7aec94a4..000000000 --- a/node_modules/cookieconsent/src/cookieconsent.js +++ /dev/null @@ -1,1748 +0,0 @@ -(function(cc) { - // stop from running again, if accidently included more than once. - if (cc.hasInitialised) return; - - var util = { - // https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex - escapeRegExp: function(str) { - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); - }, - - hasClass: function(element, selector) { - var s = ' '; - return ( - element.nodeType === 1 && - (s + element.className + s) - .replace(/[\n\t]/g, s) - .indexOf(s + selector + s) >= 0 - ); - }, - - addClass: function(element, className) { - element.className += ' ' + className; - }, - - removeClass: function(element, className) { - var regex = new RegExp('\\b' + this.escapeRegExp(className) + '\\b'); - element.className = element.className.replace(regex, ''); - }, - - interpolateString: function(str, callback) { - var marker = /{{([a-z][a-z0-9\-_]*)}}/gi; - return str.replace(marker, function(matches) { - return callback(arguments[1]) || ''; - }); - }, - - getCookie: function(name) { - var value = '; ' + document.cookie; - var parts = value.split('; ' + name + '='); - return parts.length < 2 - ? undefined - : parts - .pop() - .split(';') - .shift(); - }, - - setCookie: function(name, value, expiryDays, domain, path, secure) { - var exdate = new Date(); - exdate.setHours(exdate.getHours() + ((expiryDays || 365) * 24)); - - var cookie = [ - name + '=' + value, - 'expires=' + exdate.toUTCString(), - 'path=' + (path || '/') - ]; - - if (domain) { - cookie.push('domain=' + domain); - } - if (secure) { - cookie.push('secure'); - } - document.cookie = cookie.join(';'); - }, - - // only used for extending the initial options - deepExtend: function(target, source) { - for (var prop in source) { - if (source.hasOwnProperty(prop)) { - if ( - prop in target && - this.isPlainObject(target[prop]) && - this.isPlainObject(source[prop]) - ) { - this.deepExtend(target[prop], source[prop]); - } else { - target[prop] = source[prop]; - } - } - } - return target; - }, - - // only used for throttling the 'mousemove' event (used for animating the revoke button when `animateRevokable` is true) - throttle: function(callback, limit) { - var wait = false; - return function() { - if (!wait) { - callback.apply(this, arguments); - wait = true; - setTimeout(function() { - wait = false; - }, limit); - } - }; - }, - - // only used for hashing json objects (used for hash mapping palette objects, used when custom colours are passed through JavaScript) - hash: function(str) { - var hash = 0, - i, - chr, - len; - if (str.length === 0) return hash; - for (i = 0, len = str.length; i < len; ++i) { - chr = str.charCodeAt(i); - hash = (hash << 5) - hash + chr; - hash |= 0; - } - return hash; - }, - - normaliseHex: function(hex) { - if (hex[0] == '#') { - hex = hex.substr(1); - } - if (hex.length == 3) { - hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; - } - return hex; - }, - - // used to get text colors if not set - getContrast: function(hex) { - hex = this.normaliseHex(hex); - var r = parseInt(hex.substr(0, 2), 16); - var g = parseInt(hex.substr(2, 2), 16); - var b = parseInt(hex.substr(4, 2), 16); - var yiq = (r * 299 + g * 587 + b * 114) / 1000; - return yiq >= 128 ? '#000' : '#fff'; - }, - - // used to change color on highlight - getLuminance: function(hex) { - var num = parseInt(this.normaliseHex(hex), 16), - amt = 38, - R = (num >> 16) + amt, - B = ((num >> 8) & 0x00ff) + amt, - G = (num & 0x0000ff) + amt; - var newColour = ( - 0x1000000 + - (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 + - (B < 255 ? (B < 1 ? 0 : B) : 255) * 0x100 + - (G < 255 ? (G < 1 ? 0 : G) : 255) - ) - .toString(16) - .slice(1); - return '#' + newColour; - }, - - isMobile: function() { - return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( - navigator.userAgent - ); - }, - - isPlainObject: function(obj) { - // The code "typeof obj === 'object' && obj !== null" allows Array objects - return ( - typeof obj === 'object' && obj !== null && obj.constructor == Object - ); - }, - - traverseDOMPath: function(elem, className) { - if (!elem || !elem.parentNode) return null; - if (util.hasClass(elem, className)) return elem; - - return this.traverseDOMPath(elem.parentNode, className); - } - }; - - // valid cookie values - cc.status = { - deny: 'deny', - allow: 'allow', - dismiss: 'dismiss' - }; - - // detects the `transitionend` event name - cc.transitionEnd = (function() { - var el = document.createElement('div'); - var trans = { - t: 'transitionend', - OT: 'oTransitionEnd', - msT: 'MSTransitionEnd', - MozT: 'transitionend', - WebkitT: 'webkitTransitionEnd' - }; - - for (var prefix in trans) { - if ( - trans.hasOwnProperty(prefix) && - typeof el.style[prefix + 'ransition'] != 'undefined' - ) { - return trans[prefix]; - } - } - return ''; - })(); - - cc.hasTransition = !!cc.transitionEnd; - - // array of valid regexp escaped statuses - var __allowedStatuses = Object.keys(cc.status).map(util.escapeRegExp); - - // contains references to the custom - - -
            -
            - -
            - - -
            - - diff --git a/node_modules/paellaplayer/build/player/index.html b/node_modules/paellaplayer/build/player/index.html deleted file mode 100644 index 484c415f7..000000000 --- a/node_modules/paellaplayer/build/player/index.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - Paella Engage Example - - - - - - - - - -
            -
            - - diff --git a/node_modules/paellaplayer/build/player/javascript/bg2e-es2015.js b/node_modules/paellaplayer/build/player/javascript/bg2e-es2015.js deleted file mode 100644 index d57f56b70..000000000 --- a/node_modules/paellaplayer/build/player/javascript/bg2e-es2015.js +++ /dev/null @@ -1,18403 +0,0 @@ - -const bg = {}; -bg.version = "1.3.32 - build: 87f16ac"; -bg.utils = {}; - -Reflect.defineProperty = Reflect.defineProperty || Object.defineProperty; - -(function(win) { - win.requestAnimFrame = (function() { - return window.requestAnimationFrame || - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - window.oRequestAnimationFrame || - window.msRequestAnimationFrame || - function(callback,element) { window.setTimeout(callback,1000/60); }; - })(); - - bg.utils.initWebGLContext = function(canvas) { - let context = { - gl:null, - supported:false, - experimental:false - } - try { - context.gl = canvas.getContext("webgl",{ preserveDrawingBuffer:true }); - context.supported = context.gl!=null; - } - catch (e) { - context.supported = false; - } - - if (!context.supported) { - try { - context.gl = canvas.getContext("experimental-webgl", { preserveDrawingBuffer:true }); - context.supported = context.gl!=null; - context.experimental = true; - } - catch(e) { - } - } - - if (context) { - context.gl.uuid = Symbol(context.gl); - } - return context; - }; - - bg.utils.isBigEndian = function() { - let arr32 = new Uint32Array(1); - var arr8 = new Uint8Array(arr32.buffer); - arr32[0] = 255; - return arr32[3]==255; - }; - - bg.utils.isLittleEndian = function() { - let arr32 = new Uint32Array(1); - var arr8 = new Uint8Array(arr32.buffer); - arr32[0] = 255; - return arr32[0]==255; - }; - - class UserAgent { - - constructor(userAgentString) { - this.system = {}; - this.browser = {}; - - if (!userAgentString) { - userAgentString = navigator.userAgent; - } - this.parseOperatingSystem(userAgentString); - this.parseBrowser(userAgentString); - } - - parseOperatingSystem(userAgentString) { - this.system.OSX = /Macintosh/.test(userAgentString); - this.system.Windows = /Windows/.test(userAgentString); - this.system.iPhone = /iPhone/.test(userAgentString); - this.system.iPodTouch = /iPod/.test(userAgentString); - this.system.iPad = /iPad/.test(userAgentString); - this.system.iOS = this.system.iPhone || this.system.iPad || this.system.iPodTouch; - this.system.Android = /Android/.test(userAgentString); - this.system.Linux = (this.system.Android) ? false:/Linux/.test(userAgentString); - - if (this.system.OSX) { - this.system.OSName = "OS X"; - this.parseOSXVersion(userAgentString); - } - else if (this.system.Windows) { - this.system.OSName = "Windows"; - this.parseWindowsVersion(userAgentString); - } - else if (this.system.Linux) { - this.system.OSName = "Linux"; - this.parseLinuxVersion(userAgentString); - } - else if (this.system.iOS) { - this.system.OSName = "iOS"; - this.parseIOSVersion(userAgentString); - } - else if (this.system.Android) { - this.system.OSName = "Android"; - this.parseAndroidVersion(userAgentString); - } - } - - parseBrowser(userAgentString) { - // Safari: Version/X.X.X Safari/XXX - // Chrome: Chrome/XX.X.XX.XX Safari/XXX - // Opera: Opera/X.XX - // Firefox: Gecko/XXXXXX Firefox/XX.XX.XX - // Explorer: MSIE X.X - this.browser.Version = {}; - this.browser.Safari = /Version\/([\d\.]+) Safari\//.test(userAgentString); - if (this.browser.Safari) { - this.browser.Name = "Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Chrome = /Chrome\/([\d\.]+) Safari\//.test(userAgentString); - if (this.browser.Chrome) { - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Opera = /Opera\/[\d\.]+/.test(userAgentString); - if (this.browser.Opera) { - this.browser.Name = "Opera"; - this.browser.Vendor = "Opera Software"; - var versionString = /Version\/([\d\.]+)/.test(userAgentString); - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Firefox = /Gecko\/[\d\.]+ Firefox\/([\d\.]+)/.test(userAgentString); - if (this.browser.Firefox) { - this.browser.Name = "Firefox"; - this.browser.Vendor = "Mozilla Foundation"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Edge = /Edge\/(.*)/.test(userAgentString); - if (this.browser.Edge) { - var result = /Edge\/(.*)/.exec(userAgentString); - this.browser.Name = "Edge"; - this.browser.Chrome = false; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = result[1]; - } - - this.browser.Explorer = /MSIE ([\d\.]+)/.test(userAgentString); - if (!this.browser.Explorer) { - var re = /\Mozilla\/5.0 \(([^)]+)\) like Gecko/ - var matches = re.exec(userAgentString); - if (matches) { - re = /rv:(.*)/ - var version = re.exec(matches[1]); - this.browser.Explorer = true; - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - if (version) { - this.browser.Version.versionString = version[1]; - } - else { - this.browser.Version.versionString = "unknown"; - } - } - } - else { - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = RegExp.$1; - } - - if (this.system.iOS) { - this.browser.IsMobileVersion = true; - this.browser.MobileSafari = /Version\/([\d\.]+) Mobile/.test(userAgentString); - if (this.browser.MobileSafari) { - this.browser.Name = "Mobile Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - this.browser.Android = false; - } - else if (this.system.Android) { - this.browser.IsMobileVersion = true; - this.browser.Android = /Version\/([\d\.]+) Mobile/.test(userAgentString); - if (this.browser.MobileSafari) { - this.browser.Name = "Android Browser"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - else { - this.browser.Chrome = /Chrome\/([\d\.]+)/.test(userAgentString); - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Safari = false; - } - else { - this.browser.IsMobileVersion = false; - } - - this.parseBrowserVersion(userAgentString); - } - - parseBrowserVersion(userAgentString) { - if (/([\d]+)\.([\d]+)\.*([\d]*)/.test(this.browser.Version.versionString)) { - this.browser.Version.major = Number(RegExp.$1); - this.browser.Version.minor = Number(RegExp.$2); - this.browser.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - } - } - - parseOSXVersion(userAgentString) { - var versionString = (/Mac OS X (\d+_\d+_*\d*)/.test(userAgentString)) ? RegExp.$1:''; - this.system.Version = {}; - // Safari/Chrome - if (versionString!='') { - if (/(\d+)_(\d+)_*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - } - } - // Firefox/Opera - else { - versionString = (/Mac OS X (\d+\.\d+\.*\d*)/.test(userAgentString)) ? RegExp.$1:'Unknown'; - if (/(\d+)\.(\d+)\.*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - } - } - if (!this.system.Version.major) { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - this.system.Version.stringValue = this.system.Version.major + '.' + this.system.Version.minor + '.' + this.system.Version.revision; - switch (this.system.Version.minor) { - case 0: - this.system.Version.name = "Cheetah"; - break; - case 1: - this.system.Version.name = "Puma"; - break; - case 2: - this.system.Version.name = "Jaguar"; - break; - case 3: - this.system.Version.name = "Panther"; - break; - case 4: - this.system.Version.name = "Tiger"; - break; - case 5: - this.system.Version.name = "Leopard"; - break; - case 6: - this.system.Version.name = "Snow Leopard"; - break; - case 7: - this.system.Version.name = "Lion"; - break; - case 8: - this.system.Version.name = "Mountain Lion"; - break; - } - } - - parseWindowsVersion(userAgentString) { - this.system.Version = {}; - if (/NT (\d+)\.(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = 0; // Solo por compatibilidad - this.system.Version.stringValue = "NT " + this.system.Version.major + "." + this.system.Version.minor; - var major = this.system.Version.major; - var minor = this.system.Version.minor; - var name = 'undefined'; - if (major==5) { - if (minor==0) this.system.Version.name = '2000'; - else this.system.Version.name = 'XP'; - } - else if (major==6) { - if (minor==0) this.system.Version.name = 'Vista'; - else if (minor==1) this.system.Version.name = '7'; - else if (minor==2) this.system.Version.name = '8'; - } - } - else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - parseLinuxVersion(userAgentString) { - this.system.Version = {}; - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - this.system.Version.name = ""; - this.system.Version.stringValue = "Unknown distribution"; - } - - parseIOSVersion(userAgentString) { - this.system.Version = {}; - if (/iPhone OS (\d+)_(\d+)_*(\d*)/i.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - this.system.Version.name = "iOS"; - } - else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - parseAndroidVersion(userAgentString) { - this.system.Version = {}; - if (/Android (\d+)\.(\d+)\.*(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = (RegExp.$3) ? Number(RegExp.$3):0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } - else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - if (/Build\/([a-zA-Z]+)/.test(userAgentString)) { - this.system.Version.name = RegExp.$1; - } - else { - this.system.Version.name = "Unknown version"; - } - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } - - getInfoString() { - return navigator.userAgent; - } - } - - bg.utils.UserAgent = UserAgent; - bg.utils.userAgent = new UserAgent(); - - class Path { - get sep() { return "/"; } - - join(a,b) { - if (a.lastIndexOf(this.sep)!=a.length-1) { - return a + this.sep + b; - } - else { - return a + b; - } - } - - extension(path) { - return path.split(".").pop(); - } - - fileName(path) { - return path.split(this.sep).pop(); - } - - removeFileName(path) { - let result = path.split(this.sep); - result.pop(); - return result.join(this.sep); - } - } - - bg.utils.Path = Path; - bg.utils.path = new Path(); -})(window); - -(function() { - let s_preventImageDump = []; - let s_preventVideoDump = []; - - class ResourceProvider { - getRequest(url,onSuccess,onFail,onProgress) {} - loadImage(url,onSucces,onFail) {} - loadVideo(url,onSuccess,onFail) {} - } - - let g_videoLoaders = {}; - g_videoLoaders["mp4"] = function(url,onSuccess,onFail) { - var video = document.createElement('video'); - s_preventVideoDump.push(video); - video.crossOrigin = ""; - video.autoplay = true; - video.setAttribute("playsinline",null); - video.addEventListener('canplay',(evt) => { - let videoIndex = s_preventVideoDump.indexOf(evt.target); - if (videoIndex!=-1) { - s_preventVideoDump.splice(videoIndex,1); - } - onSuccess(event.target); - }); - video.addEventListener("error",(evt) => { - onFail(new Error(`Error loading video: ${url}`)); - }); - video.addEventListener("abort",(evt) => { - onFail(new Error(`Error loading video: ${url}`)); - }); - video.src = url; - } - g_videoLoaders["m4v"] = g_videoLoaders["mp4"]; - - class HTTPResourceProvider extends ResourceProvider { - static AddVideoLoader(type,callback) { - g_videoLoaders[type] = callback; - } - - static GetVideoLoaderForType(type) { - return g_videoLoaders[type]; - } - - static GetCompatibleVideoFormats() { - return Object.keys(g_videoLoaders); - } - - static IsVideoCompatible(videoUrl) { - let ext = Resource.GetExtension(videoUrl); - return bg.utils.HTTPResourceProvider.GetCompatibleVideoFormats().indexOf(ext)!=-1; - } - - getRequest(url,onSuccess,onFail,onProgress) { - var req = new XMLHttpRequest(); - if (!onProgress) { - onProgress = function(progress) { - console.log(`Loading ${ progress.file }: ${ progress.loaded / progress.total * 100 } %`); - } - } - req.open("GET",url,true); - req.addEventListener("load", function() { - if (req.status===200) { - onSuccess(req); - } - else { - onFail(new Error(`Error receiving data: ${req.status}, url: ${url}`)); - } - }, false); - req.addEventListener("error", function() { - onFail(new Error(`Cannot make AJAX request. Url: ${url}`)); - }, false); - req.addEventListener("progress", function(evt) { - onProgress({ file:url, loaded:evt.loaded, total:evt.total }); - }, false); - return req; - } - - loadImage(url,onSuccess,onFail) { - var img = new Image(); - s_preventImageDump.push(img); - img.crossOrigin = ""; - img.addEventListener("load",function(event) { - let imageIndex = s_preventImageDump.indexOf(event.target); - if (imageIndex!=-1) { - s_preventImageDump.splice(imageIndex,1); - } - onSuccess(event.target); - }); - img.addEventListener("error",function(event) { - onFail(new Error(`Error loading image: ${url}`)); - }); - img.addEventListener("abort",function(event) { - onFail(new Error(`Image load aborted: ${url}`)); - }); - img.src = url + '?' + bg.utils.generateUUID(); - } - - loadVideo(url,onSuccess,onFail) { - let ext = Resource.GetExtension(url); - let loader = bg.utils.HTTPResourceProvider.GetVideoLoaderForType(ext); - if (loader) { - loader.apply(this,[url,onSuccess,onFail]); - } - else { - onFail(new Error(`Could not find video loader for resource: ${ url }`)); - } - } - } - - bg.utils.ResourceProvider = ResourceProvider; - bg.utils.HTTPResourceProvider = HTTPResourceProvider; - - let g_resourceProvider = new HTTPResourceProvider(); - - class Resource { - static SetResourceProvider(provider) { - g_resourceProvider = provider; - } - - static GetResourceProvider() { - return g_resourceProvider; - } - - static GetExtension(url) { - let match = /\.([a-z0-9-_]*)(\?.*)?(\#.*)?$/i.exec(url); - return (match && match[1].toLowerCase()) || ""; - } - - static JoinUrl(url,path) { - if (url.length==0) return path; - if (path.length==0) return url; - return /\/$/.test(url) ? url + path : url + "/" + path; - } - - static IsFormat(url,formats) { - return formats.find(function(fmt) { - return fmt==this; - },Resource.GetExtension(url))!=null; - } - - static IsImage(url) { - return Resource.IsFormat(url,["jpg","jpeg","gif","png"]); - } - - static IsBinary(url,binaryFormats = ["vwglb","bg2"]) { - return Resource.IsFormat(url,binaryFormats); - } - - static IsVideo(url,videoFormats = ["mp4","m4v","ogg","ogv","m3u8","webm"]) { - return Resource.IsFormat(url,videoFormats); - } - - static LoadMultiple(urlArray,onProgress) { - let progressFiles = {} - - let progressFunc = function(progress) { - progressFiles[progress.file] = progress; - let total = 0; - let loaded = 0; - for (let key in progressFiles) { - let file = progressFiles[key]; - total += file.total; - loaded += file.loaded; - } - if (onProgress) { - onProgress({ fileList:urlArray, total:total, loaded:loaded }); - } - else { - console.log(`Loading ${ Object.keys(progressFiles).length } files: ${ loaded / total * 100}% completed`); - } - } - - let resources = []; - urlArray.forEach(function(url) { - resources.push(Resource.Load(url,progressFunc)); - }); - - let resolvingPromises = resources.map(function(promise) { - return new Promise(function(resolve) { - let payload = new Array(2); - promise.then(function(result) { - payload[0] = result; - }) - .catch(function(error) { - payload[1] = error; - }) - .then(function() { - resolve(payload); - }); - }); - }); - - let errors = []; - let results = []; - - return Promise.all(resolvingPromises) - .then(function(loadedData) { - let result = {}; - urlArray.forEach(function(url,index) { - let pl = loadedData[index]; - result[url] = pl[1] ? null : pl[0]; - }); - return result; - }); - } - - static Load(url,onProgress) { - let loader = null; - switch (true) { - case url.constructor===Array: - loader = Resource.LoadMultiple; - break; - case Resource.IsImage(url): - loader = Resource.LoadImage; - break; - case Resource.IsBinary(url): - loader = Resource.LoadBinary; - break; - case Resource.IsVideo(url): - loader = Resource.LoadVideo; - break; - case Resource.GetExtension(url)=='json': - loader = Resource.LoadJson; - break; - default: - loader = Resource.LoadText; - } - return loader(url,onProgress); - } - - static LoadText(url,onProgress) { - return new Promise(function(resolve,reject) { - g_resourceProvider.getRequest(url, - function(req) { - resolve(req.responseText); - }, - function(error) { - reject(error); - },onProgress).send(); - }); - } - - static LoadVideo(url,onProgress) { - return new Promise(function(resolve,reject) { - g_resourceProvider.loadVideo( - url, - (target) => { - resolve(target); - bg.emitImageLoadEvent(target); - }, - (err) => { - reject(err); - } - ); - }); - } - - static LoadBinary(url,onProgress) { - return new Promise(function(resolve,reject) { - var req = g_resourceProvider.getRequest(url, - function(req) { - resolve(req.response); - }, - function(error) { - reject(error); - },onProgress); - req.responseType = "arraybuffer"; - req.send(); - }); - } - - static LoadImage(url) { - return new Promise(function(resolve,reject) { - g_resourceProvider.loadImage( - url, - (target) => { - resolve(target); - bg.emitImageLoadEvent(target); - }, - (err) => { - reject(err); - } - ); - }); - } - - static LoadJson(url) { - return new Promise(function(resolve,reject) { - g_resourceProvider.getRequest(url, - function(req) { - try { - resolve(JSON.parse(req.responseText)); - } - catch(e) { - reject(new Error("Error parsing JSON data")); - } - }, - function(error) { - reject(error); - }).send(); - }); - } - } - - bg.utils.Resource = Resource; - - bg.utils.requireGlobal = function(src) { - let s = document.createElement('script'); - s.src = src; - s.type = "text/javascript"; - s.async = false; - document.getElementsByTagName('head')[0].appendChild(s); - } - -})(); -(function() { - let s_Engine = null; - - class Engine { - static Set(engine) { - s_Engine = engine; - } - - static Get() { - return s_Engine; - } - - get id() { return this._engineId; } - - get texture() { return this._texture; } - get pipeline() { return this._pipeline; } - get polyList() { return this._polyList; } - get shader() { return this._shader; } - get colorBuffer() { return this._colorBuffer; } - get textureBuffer() { return this._textureBuffer; } - get shaderSource() { return this._shaderSource; } - } - - bg.Engine = Engine; -})(); -(function() { - - class LifeCycle { - init() {} - frame(delta) {} - - displayGizmo(pipeline,matrixState) {} - - ////// Direct rendering methods: will be deprecated soon - willDisplay(pipeline,matrixState) {} - display(pipeline,matrixState,forceDraw=false) {} - didDisplay(pipeline,matrixState) {} - ////// End direct rendering methods - - ////// Render queue methods - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) {} - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) {} - didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) {} - ////// End render queue methods - - reshape(pipeline,matrixState,width,height) {} - keyDown(evt) {} - keyUp(evt) {} - mouseUp(evt) {} - mouseDown(evt) {} - mouseMove(evt) {} - mouseOut(evt) {} - mouseDrag(evt) {} - mouseWheel(evt) {} - touchStart(evt) {} - touchMove(evt) {} - touchEnd(evt) {} - - // Utility functions: do not override - // 4 frames to ensure that the reflections are fully updated - postRedisplay(frames=4) { - bg.app.MainLoop.singleton.postRedisplay(frames); - } - - postReshape() { - bg.app.MainLoop.singleton.postReshape(); - } - } - - bg.LifeCycle = LifeCycle; - -})(); -// https://github.com/xibre/FastMD5 -(function() { - !function(r){function n(r){for(var n="",t="",o=0,e=0,a=0,i=r.length;i>a;a++){var f=r.charCodeAt(a);128>f?e++:(t=2048>f?String.fromCharCode(f>>6|192,63&f|128):String.fromCharCode(f>>12|224,f>>6&63|128,63&f|128),e>o&&(n+=r.slice(o,e)),n+=t,o=e=a+1)}return e>o&&(n+=r.slice(o,i)),n}function t(r){var n,t;if(r+="",s=!1,v=w=r.length,w>63){for(o(r.substring(0,64)),i(A),s=!0,n=128;w>=n;n+=64)o(r.substring(n-64,n)),f(A);r=r.substring(n-64),w=r.length}for(d[0]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,n=0;w>n;n++)t=3&n,0===t?d[n>>2]=r.charCodeAt(n):d[n>>2]|=r.charCodeAt(n)<>2]|=h[3&n],n>55?(s?f(d):(i(d),s=!0),f([0,0,0,0,0,0,0,0,0,0,0,0,0,0,v<<3,0])):(d[14]=v<<3,void(s?f(d):i(d)))}function o(r){for(var n=16;n--;){var t=n<<2;A[n]=r.charCodeAt(t)+(r.charCodeAt(t+1)<<8)+(r.charCodeAt(t+2)<<16)+(r.charCodeAt(t+3)<<24)}}function e(r,o,e){t(o?r:n(r));var a=g[0];return u[1]=l[15&a],u[0]=l[15&(a>>=4)],u[3]=l[15&(a>>=4)],u[2]=l[15&(a>>=4)],u[5]=l[15&(a>>=4)],u[4]=l[15&(a>>=4)],u[7]=l[15&(a>>=4)],u[6]=l[15&(a>>=4)],a=g[1],u[9]=l[15&a],u[8]=l[15&(a>>=4)],u[11]=l[15&(a>>=4)],u[10]=l[15&(a>>=4)],u[13]=l[15&(a>>=4)],u[12]=l[15&(a>>=4)],u[15]=l[15&(a>>=4)],u[14]=l[15&(a>>=4)],a=g[2],u[17]=l[15&a],u[16]=l[15&(a>>=4)],u[19]=l[15&(a>>=4)],u[18]=l[15&(a>>=4)],u[21]=l[15&(a>>=4)],u[20]=l[15&(a>>=4)],u[23]=l[15&(a>>=4)],u[22]=l[15&(a>>=4)],a=g[3],u[25]=l[15&a],u[24]=l[15&(a>>=4)],u[27]=l[15&(a>>=4)],u[26]=l[15&(a>>=4)],u[29]=l[15&(a>>=4)],u[28]=l[15&(a>>=4)],u[31]=l[15&(a>>=4)],u[30]=l[15&(a>>=4)],e?u:u.join("")}function a(r,n,t,o,e,a,i){return n+=r+o+i,(n<>>a)+t<<0}function i(r){c(0,0,0,0,r),g[0]=y[0]+1732584193<<0,g[1]=y[1]-271733879<<0,g[2]=y[2]-1732584194<<0,g[3]=y[3]+271733878<<0}function f(r){c(g[0],g[1],g[2],g[3],r),g[0]=y[0]+g[0]<<0,g[1]=y[1]+g[1]<<0,g[2]=y[2]+g[2]<<0,g[3]=y[3]+g[3]<<0}function c(r,n,t,o,e){var i,f;s?(r=a((t^o)&n^o,r,n,e[0],7,25,-680876936),o=a((n^t)&r^t,o,r,e[1],12,20,-389564586),t=a((r^n)&o^n,t,o,e[2],17,15,606105819),n=a((o^r)&t^r,n,t,e[3],22,10,-1044525330)):(r=e[0]-680876937,r=(r<<7|r>>>25)-271733879<<0,o=e[1]-117830708+(2004318071&r^-1732584194),o=(o<<12|o>>>20)+r<<0,t=e[2]-1126478375+((-271733879^r)&o^-271733879),t=(t<<17|t>>>15)+o<<0,n=e[3]-1316259209+((o^r)&t^r),n=(n<<22|n>>>10)+t<<0),r=a((t^o)&n^o,r,n,e[4],7,25,-176418897),o=a((n^t)&r^t,o,r,e[5],12,20,1200080426),t=a((r^n)&o^n,t,o,e[6],17,15,-1473231341),n=a((o^r)&t^r,n,t,e[7],22,10,-45705983),r=a((t^o)&n^o,r,n,e[8],7,25,1770035416),o=a((n^t)&r^t,o,r,e[9],12,20,-1958414417),t=a((r^n)&o^n,t,o,e[10],17,15,-42063),n=a((o^r)&t^r,n,t,e[11],22,10,-1990404162),r=a((t^o)&n^o,r,n,e[12],7,25,1804603682),o=a((n^t)&r^t,o,r,e[13],12,20,-40341101),t=a((r^n)&o^n,t,o,e[14],17,15,-1502002290),n=a((o^r)&t^r,n,t,e[15],22,10,1236535329),r=a((n^t)&o^t,r,n,e[1],5,27,-165796510),o=a((r^n)&t^n,o,r,e[6],9,23,-1069501632),t=a((o^r)&n^r,t,o,e[11],14,18,643717713),n=a((t^o)&r^o,n,t,e[0],20,12,-373897302),r=a((n^t)&o^t,r,n,e[5],5,27,-701558691),o=a((r^n)&t^n,o,r,e[10],9,23,38016083),t=a((o^r)&n^r,t,o,e[15],14,18,-660478335),n=a((t^o)&r^o,n,t,e[4],20,12,-405537848),r=a((n^t)&o^t,r,n,e[9],5,27,568446438),o=a((r^n)&t^n,o,r,e[14],9,23,-1019803690),t=a((o^r)&n^r,t,o,e[3],14,18,-187363961),n=a((t^o)&r^o,n,t,e[8],20,12,1163531501),r=a((n^t)&o^t,r,n,e[13],5,27,-1444681467),o=a((r^n)&t^n,o,r,e[2],9,23,-51403784),t=a((o^r)&n^r,t,o,e[7],14,18,1735328473),n=a((t^o)&r^o,n,t,e[12],20,12,-1926607734),i=n^t,r=a(i^o,r,n,e[5],4,28,-378558),o=a(i^r,o,r,e[8],11,21,-2022574463),f=o^r,t=a(f^n,t,o,e[11],16,16,1839030562),n=a(f^t,n,t,e[14],23,9,-35309556),i=n^t,r=a(i^o,r,n,e[1],4,28,-1530992060),o=a(i^r,o,r,e[4],11,21,1272893353),f=o^r,t=a(f^n,t,o,e[7],16,16,-155497632),n=a(f^t,n,t,e[10],23,9,-1094730640),i=n^t,r=a(i^o,r,n,e[13],4,28,681279174),o=a(i^r,o,r,e[0],11,21,-358537222),f=o^r,t=a(f^n,t,o,e[3],16,16,-722521979),n=a(f^t,n,t,e[6],23,9,76029189),i=n^t,r=a(i^o,r,n,e[9],4,28,-640364487),o=a(i^r,o,r,e[12],11,21,-421815835),f=o^r,t=a(f^n,t,o,e[15],16,16,530742520),n=a(f^t,n,t,e[2],23,9,-995338651),r=a(t^(n|~o),r,n,e[0],6,26,-198630844),o=a(n^(r|~t),o,r,e[7],10,22,1126891415),t=a(r^(o|~n),t,o,e[14],15,17,-1416354905),n=a(o^(t|~r),n,t,e[5],21,11,-57434055),r=a(t^(n|~o),r,n,e[12],6,26,1700485571),o=a(n^(r|~t),o,r,e[3],10,22,-1894986606),t=a(r^(o|~n),t,o,e[10],15,17,-1051523),n=a(o^(t|~r),n,t,e[1],21,11,-2054922799),r=a(t^(n|~o),r,n,e[8],6,26,1873313359),o=a(n^(r|~t),o,r,e[15],10,22,-30611744),t=a(r^(o|~n),t,o,e[6],15,17,-1560198380),n=a(o^(t|~r),n,t,e[13],21,11,1309151649),r=a(t^(n|~o),r,n,e[4],6,26,-145523070),o=a(n^(r|~t),o,r,e[11],10,22,-1120210379),t=a(r^(o|~n),t,o,e[2],15,17,718787259),n=a(o^(t|~r),n,t,e[9],21,11,-343485551),y[0]=r,y[1]=n,y[2]=t,y[3]=o}var u=[],d=[],A=[],h=[],l="0123456789abcdef".split(""),C=[],g=[],s=!1,v=0,w=0,y=[];if(r.Int32Array)d=new Int32Array(16),A=new Int32Array(16),h=new Int32Array(4),C=new Int32Array(4),g=new Int32Array(4),y=new Int32Array(4);else{var I;for(I=0;16>I;I++)d[I]=A[I]=0;for(I=0;4>I;I++)h[I]=C[I]=g[I]=y[I]=0}h[0]=128,h[1]=32768,h[2]=8388608,h[3]=-2147483648,C[0]=0,C[1]=8,C[2]=16,C[3]=24,r.md5=r.md5||e}("undefined"==typeof global?window:global); - - bg.utils.md5 = md5; -})(); - -(function() { - function generateUUID () { // Public Domain/MIT - var d = new Date().getTime(); - if (typeof performance !== 'undefined' && typeof performance.now === 'function'){ - d += performance.now(); //use high-precision timer if available - } - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - var r = (d + Math.random() * 16) % 16 | 0; - d = Math.floor(d / 16); - return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); - }); - } - - bg.utils.generateUUID = generateUUID; -})(); -bg.app = {}; -(function() { - - class Canvas { - constructor(domElem) { - let initContext = () => { - this._context = bg.utils.initWebGLContext(domElem); - return this._context.supported; - } - - - // Attributes - this._domElem = domElem; - this._domElem.style.MozUserSelect = 'none'; - this._domElem.style.WebkitUserSelect = 'none'; - this._domElem.setAttribute("onselectstart","return false"); - - this._multisample = 1.0; - - // Initialization - if (!initContext()) { - throw new Error("Sorry, your browser does not support WebGL."); - } - } - - get multisample() { - return this._multisample; - } - - set multisample(ms) { - this._multisample = ms; - } - - get context() { - return this._context; - } - - get domElement() { - return this._domElem; - } - - get width() { - return this._domElem.clientWidth; - } - - get height() { - return this._domElem.clientHeight; - } - - screenshot(format, width, height) { - let canvasStyle = ""; - let prevSize = {} - if (width) { - height = height ? height:width; - canvasStyle = this.domElement.style.cssText; - prevSize.width = this.domElement.width; - prevSize.height = this.domElement.height; - - this.domElement.style.cssText = "top:auto;left:auto;bottom:auto;right:auto;width:" + width + "px;height:" + height + "px;"; - this.domElement.width = width; - this.domElement.height = height; - bg.app.MainLoop.singleton.windowController.reshape(width,height); - bg.app.MainLoop.singleton.windowController.postRedisplay(); - bg.app.MainLoop.singleton.windowController.display(); - } - var data = this.domElement.toDataURL(format); - if (width) { - this.domElement.style.cssText = canvasStyle; - this.domElement.width = prevSize.width; - this.domElement.height = prevSize.height; - bg.app.MainLoop.singleton.windowController.reshape(prevSize.width,prevSize.height); - bg.app.MainLoop.singleton.windowController.postRedisplay(); - bg.app.MainLoop.singleton.windowController.display(); - } - return data; - } - - } - - bg.app.Canvas = Canvas; - - class ContextObject { - constructor(context) { - this._context = context; - } - - get context() { return this._context; } - set context(c) { this._context = c; } - } - - bg.app.ContextObject = ContextObject; -})(); -(function() { - bg.app.SpecialKey = { - BACKSPACE: "Backspace", - TAB: "Tab", - ENTER: "Enter", - SHIFT: "Shift", - SHIFT_LEFT: "ShiftLeft", - SHIFT_RIGHT: "ShiftRight", - CTRL: "Control", - CTRL_LEFT: "ControlLeft", - CTRL_LEFT: "ControlRight", - ALT: "Alt", - ALT_LEFT: "AltLeft", - ALT_RIGHT: "AltRight", - PAUSE: "Pause", - CAPS_LOCK: "CapsLock", - ESCAPE: "Escape", - PAGE_UP: "PageUp", - PAGEDOWN: "PageDown", - END: "End", - HOME: "Home", - LEFT_ARROW: "ArrowLeft", - UP_ARROW: "ArrowUp", - RIGHT_ARROW: "ArrowRight", - DOWN_ARROW: "ArrowDown", - INSERT: "Insert", - DELETE: "Delete" - }; - - class EventBase { - constructor() { - this._executeDefault = false; - } - - get executeDefault() { return this._executeDefault; } - set executeDefault(d) { this._executeDefault = d; } - } - bg.app.EventBase = EventBase; - - class KeyboardEvent extends EventBase { - static IsSpecialKey(event) { - return bg.app.SpecialKey[event.code]!=null; - } - - constructor(key,event) { - super(); - this.key = key; - this.event = event; - } - - isSpecialKey() { - return KeyboardEvent.IsSpecialKey(this.event); - } - } - - bg.app.KeyboardEvent = KeyboardEvent; - - bg.app.MouseButton = { - LEFT: 0, - MIDDLE: 1, - RIGHT: 2, - NONE: -1 - }; - - class MouseEvent extends EventBase { - - constructor(button = bg.app.MouseButton.NONE, x=-1, y=-1, delta=0,event=null) { - super(); - - this.button = button; - this.x = x; - this.y = y; - this.delta = delta; - this.event = event; - } - } - - bg.app.MouseEvent = MouseEvent; - - class TouchEvent extends EventBase { - constructor(touches,event) { - super(); - this.touches = touches; - this.event = event; - } - } - - bg.app.TouchEvent = TouchEvent; - -})(); -(function() { - let s_mainLoop = null; - let s_mouseStatus = { - leftButton:false, - middleButton:false, - rightButton:false, - pos: { - x:-1, - y:-1 - } - } - Object.defineProperty(s_mouseStatus, "anyButton", { - get: function() { - return this.leftButton || this.middleButton || this.rightButton; - } - }); - let s_delta = -1; - - class Mouse { - static LeftButton() { return s_mouseStatus.leftButton; } - static MiddleButton() { return s_mouseStatus.middleButton; } - static RightButton() { return s_mouseStatus.rightButton; } - static Position() { return s_mouseStatus.pos; } - } - - bg.app.Mouse = Mouse; - - bg.app.FrameUpdate = { - AUTO: 0, - MANUAL: 1 - }; - - class MainLoop { - constructor() { - this._canvas = null; - this._windowController = null; - this._updateMode = bg.app.FrameUpdate.AUTO; - this._redisplayFrames = 1; - bg.bindImageLoadEvent(() => { - this.postRedisplay(); - }); - } - - get canvas() { return this._canvas; } - set canvas(c) { - this._canvas = new bg.app.Canvas(c); - } - get windowController() { return this._windowController; } - get updateMode() { return this._updateMode; } - set updateMode(m) { - this._updateMode = m; - if (this._updateMode==bg.app.FrameUpdate.AUTO) { - this._redisplayFrames = 1; - } - } - get redisplay() { return this._redisplayFrames>0; } - get mouseButtonStatus() { return s_mouseStatus; } - - run(windowController) { - this._windowController = windowController; - this.postRedisplay(); - this.windowController.init(); - initEvents(); - animationLoop(); - } - - // 4 frames to ensure that the reflections are fully updated - postRedisplay(frames=4) { - this._redisplayFrames = frames; - } - - postReshape() { - onResize(); - } - } - - let lastTime = 0; - function animationLoop(totalTime) { - totalTime = totalTime || 0; - requestAnimFrame(animationLoop); - let elapsed = totalTime - lastTime; - lastTime = totalTime; - onUpdate(elapsed); - } - - function initEvents() { - onResize(); - - window.addEventListener("resize", function(evt) { onResize(); }); - - if (s_mainLoop.canvas) { - let c = s_mainLoop.canvas.domElement; - c.addEventListener("mousedown", function(evt) { - if (!onMouseDown(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mousemove", function(evt) { - if (!onMouseMove(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mouseout", function(evt) { - if (!onMouseOut(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mouseover", function(evt) { - if (!onMouseOver(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("mouseup", function(evt) { - if (!onMouseUp(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - - c.addEventListener("touchstart", function(evt) { - if (!onTouchStart(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("touchmove", function(evt) { - if (!onTouchMove(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - c.addEventListener("touchend", function(evt) { - if (!onTouchEnd(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - - var mouseWheelEvt = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel"; - c.addEventListener(mouseWheelEvt, function(evt) { - if (!onMouseWheel(evt).executeDefault) { - evt.preventDefault(); - return false; - } - }); - - window.addEventListener("keydown", function(evt) { onKeyDown(evt); }); - window.addEventListener("keyup", function(evt) { onKeyUp(evt); }); - - c.oncontextmenu = function(e) { return false; }; - } - else { - throw new Error("Configuration error in MainLoop: no canvas defined"); - } - } - - function onResize() { - if (s_mainLoop.canvas && s_mainLoop.windowController) { - let multisample = s_mainLoop.canvas.multisample; - s_mainLoop.canvas.domElement.width = s_mainLoop.canvas.width * multisample; - s_mainLoop.canvas.domElement.height = s_mainLoop.canvas.height * multisample; - s_mainLoop.windowController.reshape(s_mainLoop.canvas.width * multisample, s_mainLoop.canvas.height * multisample); - } - } - - function onUpdate(elapsedTime) { - if (s_mainLoop.redisplay) { - //if (s_delta==-1) s_delta = Date.now(); - //s_mainLoop.windowController.frame((Date.now() - s_delta) * 2); - //s_delta = Date.now(); - s_mainLoop.windowController.frame(elapsedTime); - if (s_mainLoop.updateMode==bg.app.FrameUpdate.AUTO) { - s_mainLoop._redisplayFrames = 1; - } - else { - s_mainLoop._redisplayFrames--; - } - s_mainLoop.windowController.display(); - } - } - - function onMouseDown(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - switch (event.button) { - case bg.app.MouseButton.LEFT: - s_mouseStatus.leftButton = true; - break; - case bg.app.MouseButton.MIDDLE: - s_mouseStatus.middleButton = true; - break; - case bg.app.MouseButton.RIGHT: - s_mouseStatus.rightButton = true; - break; - } - - let bgEvent = new bg.app.MouseEvent(event.button,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,event); - s_mainLoop.windowController.mouseDown(bgEvent); - return bgEvent; - } - - function onMouseMove(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - let evt = new bg.app.MouseEvent(bg.app.MouseButton.NONE, - s_mouseStatus.pos.x, - s_mouseStatus.pos.y, - 0, - event); - s_mainLoop.windowController.mouseMove(evt); - if (s_mouseStatus.anyButton) { - s_mainLoop.windowController.mouseDrag(evt); - } - return evt; - } - - function onMouseOut() { - let bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.NONE,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseOut(bgEvt); - if (s_mouseStatus.leftButton) { - s_mouseStatus.leftButton = false; - bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.LEFT,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseUp(bgEvt); - } - if (s_mouseStatus.middleButton) { - s_mouseStatus.middleButton = false; - bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.MIDDLE,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseUp(bgEvt); - } - if (s_mouseStatus.rightButton) { - bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.RIGHT,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,{}); - s_mainLoop.windowController.mouseUp(bgEvt); - s_mouseStatus.rightButton = false; - } - return bgEvt; - } - - function onMouseOver(event) { - return onMouseMove(event); - } - - function onMouseUp(event) { - switch (event.button) { - case bg.app.MouseButton.LEFT: - s_mouseStatus.leftButton = false; - break; - case bg.app.MouseButton.MIDDLE: - s_mouseStatus.middleButton = false; - break; - case bg.app.MouseButton.RIGHT: - s_mouseStatus.rightButton = false; - break; - } - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - let bgEvt = new bg.app.MouseEvent(event.button,s_mouseStatus.pos.x,s_mouseStatus.pos.y,0,event) - s_mainLoop.windowController.mouseUp(bgEvt); - return bgEvt; - } - - function onMouseWheel(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let multisample = s_mainLoop.canvas.multisample; - s_mouseStatus.pos.x = (event.clientX - offset.left) * multisample; - s_mouseStatus.pos.y = (event.clientY - offset.top) * multisample; - let delta = event.wheelDelta ? event.wheelDelta * -1:event.detail * 10; - let bgEvt = new bg.app.MouseEvent(bg.app.MouseButton.NONE,s_mouseStatus.pos.x,s_mouseStatus.pos.y,delta,event) - s_mainLoop.windowController.mouseWheel(bgEvt); - return bgEvt; - } - - function getTouchEvent(event) { - let offset = s_mainLoop.canvas.domElement.getBoundingClientRect(); - let touches = []; - for (let i=0; i { - source.params.forEach((param) => { - if (param) { - if (param.role=="buffer") { - this._inputVars[param.target] = param.name; - inputAttribs.push(param.name); - } - else if (param.role=="value") { - inputVars.push(param.name); - } - } - }); - - this._shader.addShaderSource(source.type,source.toString()); - }); - this._shader.link(); - if (!this._shader.status) { - bg.log(this._shader.compileError); - if (this._shader.compileErrorSource) { - bg.log("Shader source:"); - bg.log(this._shader.compileErrorSource); - } - bg.log(this._shader.linkError); - } - else { - this._shader.initVars(inputAttribs,inputVars); - } - } - - // This function is used to setup shader variables that are the same for all - // scene object, such as lights or color correction - beginDraw() { - - } - - // This function is called before draw each polyList. The material properties will be - // set in this.material - setupVars() { - // pass the input vars values to this.shader - } - - setActive() { - this.shader.setActive(); - this.beginDraw(); - } - - clearActive() { - this.shader.clearActive(); - } - - bindPolyList(plist) { - var s = this.shader; - if (this.inputVars.vertex) { - s.setInputBuffer(this.inputVars.vertex, plist.vertexBuffer, 3); - } - if (this.inputVars.normal) { - s.setInputBuffer(this.inputVars.normal, plist.normalBuffer, 3); - } - if (this.inputVars.tex0) { - s.setInputBuffer(this.inputVars.tex0, plist.texCoord0Buffer, 2); - } - if (this.inputVars.tex1) { - s.setInputBuffer(this.inputVars.tex1, plist.texCoord1Buffer, 2); - } - if (this.inputVars.tex2) { - s.setInputBuffer(this.inputVars.tex2, plist.texCoord2Buffer, 2); - } - if (this.inputVars.color) { - s.setInputBuffer(this.inputVars.color, plist.colorBuffer, 4); - } - if (this.inputVars.tangent) { - s.setInputBuffer(this.inputVars.tangent, plist.tangentBuffer, 3); - } - this.setupVars(); - } - - unbind() { - var s = this.shader; - if (this.inputVars.vertex) { - s.disableInputBuffer(this.inputVars.vertex); - } - if (this.inputVars.normal) { - s.disableInputBuffer(this.inputVars.normal); - } - if (this.inputVars.tex0) { - s.disableInputBuffer(this.inputVars.tex0); - } - if (this.inputVars.tex1) { - s.disableInputBuffer(this.inputVars.tex1); - } - if (this.inputVars.tex2) { - s.disableInputBuffer(this.inputVars.tex2); - } - if (this.inputVars.color) { - s.disableInputBuffer(this.inputVars.color); - } - if (this.inputVars.tangent) { - s.disableInputBuffer(this.inputVars.tangent); - } - } - } - - bg.base.Effect = Effect; - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class TextureEffect extends Effect { - constructor(context) { - super(context); - - this._frame = new bg.base.PolyList(context); - - this._frame.vertex = [ 1, 1, 0, -1, 1, 0, -1,-1, 0,1,-1, 0 ]; - this._frame.texCoord0 = [ 1, 1, 0, 1, 0, 0, 1, 0 ]; - this._frame.index = [ 0, 1, 2, 2, 3, 0 ]; - - this._frame.build(); - - this.rebuildShaders(); - } - - rebuildShaders() { - this.setupShaderSource([ - this.vertexShaderSource, - this.fragmentShaderSource - ]); - } - - get vertexShaderSource() { - if (!this._vertexShaderSource) { - this._vertexShaderSource = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - this._vertexShaderSource.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - this._vertexShaderSource.setMainBody(` - gl_Position = vec4(inVertex,1.0); - fsTexCoord = inTex0;`); - } - } - return this._vertexShaderSource; - } - - get fragmentShaderSource() { - if (!this._fragmentShaderSource) { - this._fragmentShaderSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - this._fragmentShaderSource.addParameter( - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ); - - if (bg.Engine.Get().id=="webgl1") { - this._fragmentShaderSource.setMainBody(` - gl_FragColor = vec4(1.0,0.0,0.0,1.0);`); - } - } - return this._fragmentShaderSource; - } - - //setupVars() { - // this._surface contains the surface passed to drawSurface - //} - - drawSurface(surface) { - this.setActive(); - this._surface = surface; - this.bindPolyList(this._frame); - this._frame.draw(); - this.unbind(); - this.clearActive(); - } - - } - - bg.base.TextureEffect = TextureEffect; - -})(); -(function() { - - class LoaderPlugin { - - acceptType(url,data) { return false; } - load(context,url,data) { - return new Promise((resolve,reject) => { - reject(new Error("Not implemented")); - }); - } - - } - - bg.base.LoaderPlugin = LoaderPlugin; - - let s_loaderPlugins = []; - - function loadUrl(context,url,onProgress = null,extraData = null) { - return new Promise((accept,reject) => { - bg.utils.Resource.Load(url,onProgress) - .then(function(data) { - return Loader.LoadData(context,url,data,extraData); - }) - - .then((result,extendedData) => { - accept(result,extendedData); - }) - - .catch(function(err) { - reject(err); - }); - }); - } - - function loadUrlArray(context,url,onProgress = null,extraData = null) { - return new Promise((accept,reject) => { - bg.utils.Resource.LoadMultiple(url,onProgress) - .then((result) => { - let promises = []; - - for (let itemUrl in result) { - let data = result[itemUrl]; - promises.push(loadData(context,itemUrl,data,extraData)); - } - - return Promise.all(promises); - }) - .then((loadedResults) => { - let resolvedData = {} - url.forEach((itemUrl,index) => { - resolvedData[itemUrl] = loadedResults[index]; - }) - accept(resolvedData); - }) - .catch((err) => { - reject(err); - }) - }) - } - - function loadData(context,url,data,extraData = null) { - return new Promise((accept,reject) => { - let selectedPlugin = null; - s_loaderPlugins.some((plugin) => { - if (plugin.acceptType(url,data)) { - selectedPlugin = plugin; - return true; - } - }) - - if (selectedPlugin) { - if (!extraData) { - extraData = {}; - } - accept(selectedPlugin.load(context,url,data,extraData)); - } - else { - return reject(new Error("No suitable plugin found for load " + url)); - } - }); - } - - class Loader { - static RegisterPlugin(p) { s_loaderPlugins.push(p); } - - static Load(context,url,onProgress = null,extraData = null) { - if (Array.isArray(url)) { - return loadUrlArray(context,url,onProgress,extraData); - } - else { - return loadUrl(context,url,onProgress,extraData); - } - } - - static LoadData(context,url,data,extraData = null) { - return loadData(context,url,data,extraData); - } - } - - bg.base.Loader = Loader; - -})(); -(function() { - // NOTE: All the writer functions and classes are intended to be used - // only in an Electron.js application - if (!bg.isElectronApp) { - return false; - } - - class WriterPlugin { - acceptType(url,data) { return false; } - write(url,data) {} - } - - bg.base.WriterPlugin = WriterPlugin; - - let s_writerPlugins = []; - - class Writer { - static RegisterPlugin(p) { s_writerPlugins.push(p); } - - static Write(url,data) { - return new Promise((resolve,reject) => { - let selectedPlugin = null; - s_writerPlugins.some((plugin) => { - if (plugin.acceptType(url,data)) { - selectedPlugin = plugin; - return true; - } - }); - - if (selectedPlugin) { - resolve(selectedPlugin.write(url,data)); - } - else { - reject(new Error("No suitable plugin found for write " + url)); - } - }) - } - - static PrepareDirectory(dir) { - let targetDir = Writer.ToSystemPath(dir); - const fs = require('fs'); - const path = require('path'); - const sep = path.sep; - const initDir = path.isAbsolute(targetDir) ? sep : ''; - targetDir.split(sep).reduce((parentDir,childDir) => { - const curDir = path.resolve(parentDir, childDir); - if (!fs.existsSync(curDir)) { - fs.mkdirSync(curDir); - } - return curDir; - }, initDir); - } - - static StandarizePath(inPath) { - return inPath.replace(/\\/g,'/'); - } - - static ToSystemPath(inPath) { - const path = require('path'); - const sep = path.sep; - return inPath.replace(/\\/g,sep).replace(/\//g,sep); - } - - static CopyFile(source,target) { - return new Promise((resolve,reject) => { - const fs = require("fs"); - const path = require("path"); - let cbCalled = false; - - source = Writer.StandarizePath(path.resolve(source)); - target = Writer.StandarizePath(path.resolve(target)); - - if (source==target) { - resolve(); - } - else { - let rd = fs.createReadStream(source); - rd.on("error", function(err) { - done(err); - }); - let wr = fs.createWriteStream(target); - wr.on("error", function(err) { - done(err); - }); - wr.on("close", function(ex) { - done(); - }); - rd.pipe(wr); - - function done(err) { - if (!cbCalled) { - err ? reject(err) : resolve(); - cbCalled = true; - } - } - } - }) - } - } - - bg.base.Writer = Writer; -})(); -(function() { - // NOTE: this plugin is intended to be used only in an Electron.js app - if (!bg.isElectronApp) { - return false; - } - - let fs = require('fs'); - let path = require('path'); - - function writeTexture(texture,fileData) { - if (texture) { - let dstPath = bg.base.Writer.StandarizePath(fileData.path).split("/"); - dstPath.pop(); - let paths = { - src: bg.base.Writer.StandarizePath(texture.fileName), - dst: null - }; - - let srcFileName = paths.src.split("/").pop(); - dstPath.push(srcFileName); - dstPath = dstPath.join("/"); - paths.dst = dstPath; - - if (paths.src!=paths.dst) { - fileData.copyFiles.push(paths); - } - return srcFileName; - } - else { - return ""; - } - } - function getMaterialString(fileData) { - let mat = []; - fileData.node.drawable.forEach((plist,material) => { - mat.push({ - "name": plist.name, - "class": "GenericMaterial", - - "diffuseR": material.diffuse.r, - "diffuseG": material.diffuse.g, - "diffuseB": material.diffuse.b, - "diffuseA": material.diffuse.a, - - "specularR": material.specular.r, - "specularG": material.specular.g, - "specularB": material.specular.b, - "specularA": material.specular.a, - - "shininess": material.shininess, - "refractionAmount": material.refractionAmount, - "reflectionAmount": material.reflectionAmount, - "lightEmission": material.lightEmission, - - "textureOffsetX": material.textureOffset.x, - "textureOffsetY": material.textureOffset.y, - "textureScaleX": material.textureScale.x, - "textureScaleY": material.textureScale.y, - - "lightmapOffsetX": material.lightmapOffset.x, - "lightmapOffsetY": material.lightmapOffset.y, - "lightmapScaleX": material.lightmapScale.x, - "lightmapScaleY": material.lightmapScale.y, - - "normalMapOffsetX": material.normalMapOffset.x, - "normalMapOffsetY": material.normalMapOffset.y, - "normalMapScaleX": material.normalMapScale.x, - "normalMapScaleY": material.normalMapScale.y, - - "castShadows": material.castShadows, - "receiveShadows": material.receiveShadows, - - "alphaCutoff": material.alphaCutoff, - - "shininessMaskChannel": material.shininessMaskChannel, - "invertShininessMask": material.shininessMaskInvert, - "lightEmissionMaskChannel": material.lightEmissionMaskChannel, - "invertLightEmissionMask": material.lightEmissionMaskInvert, - - "displacementFactor": 0, - "displacementUV": 0, - "tessDistanceFarthest": 40.0, - "tessDistanceFar": 30.0, - "tessDistanceNear": 15.0, - "tessDistanceNearest": 8.0, - "tessFarthestLevel": 1, - "tessFarLevel": 1, - "tessNearLevel": 1, - "tessNearestLevel": 1, - - "reflectionMaskChannel": material.reflectionMaskChannel, - "invertReflectionMask": material.reflectionMaskInvert, - - "roughness": material.roughness, - "roughnessMaskChannel": material.roughnessMaskChannel, - "invertRoughnessMask": material.roughnessMaskInvert, - - "cullFace": material.cullFace, - - "unlit": material.unlit, - - "texture": writeTexture(material.texture,fileData), - "lightmap": writeTexture(material.lightmap,fileData), - "normalMap": writeTexture(material.normalMap,fileData), - "shininessMask": writeTexture(material.shininessMask,fileData), - "lightEmissionMask": writeTexture(material.lightEmissionMask,fileData), - "displacementMap": "", - "reflectionMask": writeTexture(material.reflectionMask,fileData), - "roughnessMask": writeTexture(material.roughnessMask,fileData), - "visible": plist.visible, - "visibleToShadows": plist.visibleToShadows, - "groupName": plist.groupName - }); - }); - return JSON.stringify(mat); - } - - function getJointString(fileData) { - let joints = {}; - let inJoint = fileData.node.component("bg.scene.InputChainJoint"); - let outJoint = fileData.node.component("bg.scene.OutputChainJoint"); - if (inJoint) { - joints.input = { - "type":"LinkJoint", - "offset":[ - inJoint.joint.offset.x, - inJoint.joint.offset.y, - inJoint.joint.offset.z - ], - "pitch": inJoint.joint.pitch, - "roll": inJoint.joint.roll, - "yaw": inJoint.joint.yaw - }; - } - if (outJoint) { - joints.output = [{ - "type":"LinkJoint", - "offset":[ - outJoint.joint.offset.x, - outJoint.joint.offset.y, - outJoint.joint.offset.z - ], - "pitch": outJoint.joint.pitch, - "roll": outJoint.joint.roll, - "yaw": outJoint.joint.yaw - }]; - } - return JSON.stringify(joints); - } - - function ensurePolyListName(fileData) { - let plistNames = []; - let plIndex = 0; - fileData.node.drawable.forEach((plist,matName) => { - let plName = plist.name; - if (!plName || plistNames.indexOf(plName)!=-1) { - do { - plName = "polyList_" + plIndex; - ++plIndex; - } - while (plistNames.indexOf(plName)!=-1); - plist.name = plName; - } - plistNames.push(plName); - }); - } - - class FileData { - constructor(path,node) { - this._path = path; - this._node = node; - this._copyFiles = []; - this._stream = fs.createWriteStream(path); - } - - get path() { return this._path; } - get node() { return this._node; } - get copyFiles() { return this._copyFiles; } - - get stream() { return this._stream; } - - writeUInt(number) { - let buffer = Buffer.alloc(4); - buffer.writeUInt32BE(number,0); - this.stream.write(buffer); - } - - writeBlock(blockName) { - this.stream.write(Buffer.from(blockName,"utf-8")); - } - - writeString(stringData) { - this.writeUInt(stringData.length); - this.stream.write(Buffer.from(stringData,"utf-8")); - } - - writeBuffer(name,arrayBuffer) { - this.writeBlock(name); - this.writeUInt(arrayBuffer.length); - let buffer = Buffer.alloc(4 * arrayBuffer.length); - if (name=="indx") { - arrayBuffer.forEach((d,i) => buffer.writeUInt32BE(d,i * 4)); - } - else { - arrayBuffer.forEach((d,i) => buffer.writeFloatBE(d,i * 4)); - } - this.stream.write(buffer); - } - - writeTextures() { - let promises = []; - this.copyFiles.forEach((copyData) => { - promises.push(new Promise((resolve,reject) => { - let rd = fs.createReadStream(copyData.src); - rd.on('error',rejectCleanup); - let wr = fs.createWriteStream(copyData.dst); - wr.on('error',rejectCleanup); - function rejectCleanup(err) { - rd.destroy(); - wr.end(); - reject(err); - } - wr.on('finish',resolve); - rd.pipe(wr); - })) - }); - return Promise.all(promises); - } - } - - function writeHeader(fileData) { - let buffer = Buffer.alloc(4); - [ - 0, // big endian - 1, // major version - 2, // minor version - 0 // review - ].forEach((d,i) => buffer.writeInt8(d,i)); - fileData.stream.write(buffer); - - // Header - fileData.writeBlock("hedr"); - - // Ensure that all poly list have name and material name - ensurePolyListName(fileData); - - // Number of polyLists - let drw = fileData.node.drawable; - let plistItems = 0; - drw.forEach(() => plistItems++); - fileData.writeUInt(plistItems); - - // Material header - fileData.writeBlock("mtrl"); - fileData.writeString(getMaterialString(fileData)); - - // Joints header - fileData.writeBlock("join"); - fileData.writeString(getJointString(fileData)); - } - - function writePolyList(fileData,plist,material,trx) { - //let buffer = Buffer.alloc(4); - //fileData.stream.write(Buffer.from("plst","utf-8")); // poly list - fileData.writeBlock("plst"); - - // Poly list name - fileData.writeBlock("pnam"); - fileData.writeString(plist.name); - - // Material name, the same as plist name in version 1.2.0 - fileData.writeBlock("mnam"); - fileData.writeString(plist.name); - - fileData.writeBuffer("varr",plist.vertex); - fileData.writeBuffer("narr",plist.normal); - fileData.writeBuffer("t0ar",plist.texCoord0); - fileData.writeBuffer("t1ar",plist.texCoord1); - fileData.writeBuffer("indx",plist.index); - } - - function writeNode(fileData) { - writeHeader(fileData); - fileData.node.drawable.forEach((plist,mat,trx) => { - writePolyList(fileData,plist,mat,trx); - }); - fileData.writeBlock("endf"); - fileData.stream.end(); - } - - class Bg2WriterPlugin extends bg.base.WriterPlugin { - acceptType(url,data) { - let ext = url.split(".").pop(); - return /bg2/i.test(ext) || /vwglb/i.test(ext); - } - - write(url,data) { - return new Promise((resolve,reject) => { - if (!data || !data instanceof bg.scene.Node || !data.drawable) { - reject(new Error("Invalid data format. Expecting scene node.")); - } - let fileData = new FileData(url,data); - - try { - writeNode(fileData); - fileData.writeTextures() - .then(() => resolve()) - .catch((err) => reject(err)); - } - catch (err) { - reject(err); - } - }) - } - } - - bg.base.Bg2WriterPlugin = Bg2WriterPlugin; -})(); -(function() { - - class Bg2matLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - return bg.utils.Resource.GetExtension(url)=="bg2mat"; - } - - load(context,url,data) { - return new Promise((resolve,reject) => { - if (data) { - try { - if (typeof(data)=="string") { - data = JSON.parse(data); - } - let promises = []; - let basePath = url.substring(0,url.lastIndexOf('/')+1); - - data.forEach((matData) => { - promises.push(bg.base.Material.FromMaterialDefinition(context,matData,basePath)); - }); - - Promise.all(promises) - .then((result) => { - resolve(result); - }); - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading material. Data is null.")); - } - }); - } - } - - bg.base.Bg2matLoaderPlugin = Bg2matLoaderPlugin; - -})(); -(function() { - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class DrawTextureEffect extends bg.base.TextureEffect { - constructor(context) { - super(context); - - let vertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - let fragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - vertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - fragment.addParameter([ - lib().inputs.material.texture, - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - vertex.setMainBody(` - gl_Position = vec4(inVertex,1.0); - fsTexCoord = inTex0;`); - fragment.setMainBody("gl_FragColor = texture2D(inTexture,fsTexCoord);"); - } - - this.setupShaderSource([ - vertex, - fragment - ]); - } - - setupVars() { - let texture = null; - if (this._surface instanceof bg.base.Texture) { - texture = this._surface; - } - else if (this._surface instanceof bg.base.RenderSurface) { - texture = this._surface.getTexture(0); - } - - if (texture) { - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - } - } - } - - bg.base.DrawTextureEffect = DrawTextureEffect; -})(); -(function() { - let shaders = {}; - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - let s_vertexSource = null; - let s_fragmentSource = null; - - function vertexShaderSource() { - if (!s_vertexSource) { - s_vertexSource = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_vertexSource.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.normal, - lib().inputs.buffers.tangent, - lib().inputs.buffers.tex0, - lib().inputs.buffers.tex1 - ]); - - s_vertexSource.addParameter(lib().inputs.matrix.all); - - s_vertexSource.addParameter([ - { name:"inLightProjectionMatrix", dataType:"mat4", role:"value" }, - { name:"inLightViewMatrix", dataType:"mat4", role:"value" }, - ]); - - s_vertexSource.addParameter([ - { name:"fsPosition", dataType:"vec3", role:"out" }, - { name:"fsTex0Coord", dataType:"vec2", role:"out" }, - { name:"fsTex1Coord", dataType:"vec2", role:"out" }, - { name:"fsNormal", dataType:"vec3", role:"out" }, - { name:"fsTangent", dataType:"vec3", role:"out" }, - { name:"fsBitangent", dataType:"vec3", role:"out" }, - { name:"fsSurfaceToView", dataType:"vec3", role:"out" }, - - { name:"fsVertexPosFromLight", dataType:"vec4", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_vertexSource.setMainBody(` - mat4 ScaleMatrix = mat4(0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 0.5, 0.0, - 0.5, 0.5, 0.5, 1.0); - - vec4 viewPos = inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - gl_Position = inProjectionMatrix * viewPos; - - fsNormal = normalize((inNormalMatrix * vec4(inNormal,1.0)).xyz); - fsTangent = normalize((inNormalMatrix * vec4(inTangent,1.0)).xyz); - fsBitangent = cross(fsNormal,fsTangent); - - fsVertexPosFromLight = ScaleMatrix * inLightProjectionMatrix * inLightViewMatrix * inModelMatrix * vec4(inVertex,1.0); - - fsTex0Coord = inTex0; - fsTex1Coord = inTex1; - fsPosition = viewPos.xyz;`); - } - } - return s_vertexSource; - } - - function fragmentShaderSource() { - if (!s_fragmentSource) { - s_fragmentSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - s_fragmentSource.addParameter(lib().inputs.material.all); - s_fragmentSource.addParameter(lib().inputs.lightingForward.all); - s_fragmentSource.addParameter(lib().inputs.shadows.all); - s_fragmentSource.addParameter(lib().inputs.colorCorrection.all); - s_fragmentSource.addParameter([ - { name:"fsPosition", dataType:"vec3", role:"in" }, - { name:"fsTex0Coord", dataType:"vec2", role:"in" }, - { name:"fsTex1Coord", dataType:"vec2", role:"in" }, - { name:"fsNormal", dataType:"vec3", role:"in" }, - { name:"fsTangent", dataType:"vec3", role:"in" }, - { name:"fsBitangent", dataType:"vec3", role:"in" }, - { name:"fsSurfaceToView", dataType:"vec3", role:"in" }, - - { name:"fsVertexPosFromLight", dataType:"vec4", role:"in" }, - - { name:"inCubeMap", dataType:"samplerCube", role:"value" }, - { name:"inLightEmissionFactor", dataType:"float", role:"value" } - ]); - - s_fragmentSource.addFunction(lib().functions.materials.all); - s_fragmentSource.addFunction(lib().functions.colorCorrection.all); - s_fragmentSource.addFunction(lib().functions.utils.unpack); - s_fragmentSource.addFunction(lib().functions.utils.random); - s_fragmentSource.addFunction(lib().functions.lighting.all); - s_fragmentSource.addFunction(lib().functions.blur.blurCube); - - if (bg.Engine.Get().id=="webgl1") { - s_fragmentSource.setMainBody(` - vec4 diffuseColor = samplerColor(inTexture,fsTex0Coord,inTextureOffset,inTextureScale); - vec4 lightmapColor = samplerColor(inLightMap,fsTex1Coord,inLightMapOffset,inLightMapScale); - - if (inUnlit && diffuseColor.a>=inAlphaCutoff) { - gl_FragColor = diffuseColor * lightmapColor; - } - else if (diffuseColor.a>=inAlphaCutoff) { - vec3 normalMap = samplerNormal(inNormalMap,fsTex0Coord,inNormalMapOffset,inNormalMapScale); - // This doesn't work on many Mac Intel GPUs - // vec3 frontFacingNormal = fsNormal; - // if (!gl_FrontFacing) { - // frontFacingNormal *= -1.0; - // } - normalMap = combineNormalWithMap(fsNormal,fsTangent,fsBitangent,normalMap); - vec4 shadowColor = vec4(1.0); - if (inReceiveShadows) { - shadowColor = getShadowColor(fsVertexPosFromLight,inShadowMap,inShadowMapSize,inShadowType,inShadowStrength,inShadowBias,inShadowColor); - } - - vec4 specular = specularColor(inSpecularColor,inShininessMask,fsTex0Coord,inTextureOffset,inTextureScale, - inShininessMaskChannel,inShininessMaskInvert); - float lightEmission = applyTextureMask(inLightEmission, - inLightEmissionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inLightEmissionMaskChannel,inLightEmissionMaskInvert); - diffuseColor = diffuseColor * inDiffuseColor * lightmapColor; - - vec4 light = vec4(0.0,0.0,0.0,1.0); - vec4 specularColor = vec4(0.0,0.0,0.0,1.0); - // This doesn't work on A11 and A12 chips on Apple devices. - // for (int i=0; i<${ bg.base.MAX_FORWARD_LIGHTS}; ++i) { - // if (i>=inNumLights) break; - // light.rgb += getLight( - // inLightType[i], - // inLightAmbient[i], inLightDiffuse[i], inLightSpecular[i],inShininess, - // inLightPosition[i],inLightDirection[i], - // inLightAttenuation[i].x,inLightAttenuation[i].y,inLightAttenuation[i].z, - // inSpotCutoff[i],inSpotExponent[i],inLightCutoffDistance[i], - // fsPosition,normalMap, - // diffuseColor,specular,shadowColor, - // specularColor - // ).rgb; - // light.rgb += specularColor.rgb; - // } - - // Workaround for A11 and A12 chips - if (inNumLights>0) { - light.rgb += getLight( - inLightType[0], - inLightAmbient[0], inLightDiffuse[0], inLightSpecular[0],inShininess, - inLightPosition[0],inLightDirection[0], - inLightAttenuation[0].x,inLightAttenuation[0].y,inLightAttenuation[0].z, - inSpotCutoff[0],inSpotExponent[0],inLightCutoffDistance[0], - fsPosition,normalMap, - diffuseColor,specular,shadowColor, - specularColor - ).rgb; - light.rgb += specularColor.rgb; - } - if (inNumLights>1) { - light.rgb += getLight( - inLightType[1], - inLightAmbient[1], inLightDiffuse[1], inLightSpecular[1],inShininess, - inLightPosition[1],inLightDirection[1], - inLightAttenuation[1].x,inLightAttenuation[1].y,inLightAttenuation[1].z, - inSpotCutoff[0],inSpotExponent[1],inLightCutoffDistance[1], - fsPosition,normalMap, - diffuseColor,specular,shadowColor, - specularColor - ).rgb; - light.rgb += specularColor.rgb; - } - - vec3 cameraPos = vec3(0.0); - vec3 cameraVector = fsPosition - cameraPos; - vec3 lookup = reflect(cameraVector,normalMap); - - // Roughness using gaussian blur has been deactivated because it is very inefficient - //float dist = distance(fsPosition,cameraPos); - //float maxRough = 50.0; - //float rough = max(inRoughness * 10.0,1.0); - //rough = max(rough*dist,rough); - //float blur = min(rough,maxRough); - //vec3 cubemapColor = blurCube(inCubeMap,lookup,int(blur),vec2(10),dist).rgb; - - vec3 cubemapColor = textureCube(inCubeMap,lookup).rgb; - - float reflectionAmount = applyTextureMask(inReflection, - inReflectionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inReflectionMaskChannel,inReflectionMaskInvert); - - light.rgb = clamp(light.rgb + (lightEmission * diffuseColor.rgb * 10.0), vec3(0.0), vec3(1.0)); - - - gl_FragColor = vec4(light.rgb * (1.0 - reflectionAmount) + cubemapColor * reflectionAmount * diffuseColor.rgb, diffuseColor.a); - } - else { - discard; - }` - ); - } - } - return s_fragmentSource; - } - - class ColorCorrectionSettings { - constructor() { - this._hue = 1; - this._saturation = 1; - this._lightness = 1; - this._brightness = 0.5; - this._contrast = 0.5; - } - - set hue(h) { this._hue = h; } - get hue() { return this._hue; } - set saturation(s) { this._saturation = s; } - get saturation() { return this._saturation; } - set lightness(l) { this._lightness = l; } - get lightness() { return this._lightness; } - set brightness(b) { this._brightness = b; } - get brightness() { return this._brightness; } - set contrast(c) { this._contrast = c; } - get contrast() { return this._contrast; } - - apply(shader,varNames={ hue:'inHue', - saturation:'inSaturation', - lightness:'inLightness', - brightness:'inBrightness', - contrast:'inContrast' }) - { - shader.setValueFloat(varNames['hue'], this._hue); - shader.setValueFloat(varNames['saturation'], this._saturation); - shader.setValueFloat(varNames['lightness'], this._lightness); - shader.setValueFloat(varNames['brightness'], this._brightness); - shader.setValueFloat(varNames['contrast'], this._contrast); - } - } - - bg.base.ColorCorrectionSettings = ColorCorrectionSettings; - - class ForwardEffect extends bg.base.Effect { - constructor(context) { - super(context); - this._material = null; - this._light = null; - this._lightTransform = bg.Matrix4.Identity(); - - this._lightArray = new bg.base.LightArray(); - - this._shadowMap = null; - - let sources = [ - vertexShaderSource(), - fragmentShaderSource() - ]; - this.setupShaderSource(sources); - this._colorCorrection = new bg.base.ColorCorrectionSettings(); - } - - get material() { return this._material; } - set material(m) { this._material = m; } - - // Individual light mode - get light() { return this._light; } - set light(l) { this._light = l; this._lightArray.reset(); } - get lightTransform() { return this._lightTransform; } - set lightTransform(trx) { this._lightTransform = trx; this._lightArray.reset();} - - // Multiple light mode: use light arrays - get lightArray() { return this._lightArray; } - - set shadowMap(sm) { this._shadowMap = sm; } - get shadowMap() { return this._shadowMap; } - - get colorCorrection() { return this._colorCorrection; } - set colorCorrection(cc) { this._colorCorrection = cc; } - - beginDraw() { - if (this._light) { - // Individual mode: initialize light array - this.lightArray.reset(); - this.lightArray.push(this.light,this.lightTransform); - } - - if (this.lightArray.numLights) { - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - - // Update lights positions and directions using the current view matrix - this.lightArray.updatePositionAndDirection(viewMatrix); - - // Forward render only supports one shadow map - let lightTransform = this.shadowMap ? this.shadowMap.viewMatrix : this.lightArray.shadowLightTransform; - this.shader.setMatrix4("inLightProjectionMatrix", this.shadowMap ? this.shadowMap.projection : this.lightArray.shadowLight.projection); - let shadowColor = this.shadowMap ? this.shadowMap.shadowColor : bg.Color.Transparent(); - - let blackTex = bg.base.TextureCache.BlackTexture(this.context); - this.shader.setMatrix4("inLightViewMatrix",lightTransform); - this.shader.setValueInt("inShadowType",this._shadowMap ? this._shadowMap.shadowType : 0); - this.shader.setTexture("inShadowMap",this._shadowMap ? this._shadowMap.texture : blackTex,bg.base.TextureUnit.TEXTURE_5); - this.shader.setVector2("inShadowMapSize",this._shadowMap ? this._shadowMap.size : new bg.Vector2(32,32)); - this.shader.setValueFloat("inShadowStrength",this.lightArray.shadowLight.shadowStrength); - this.shader.setVector4("inShadowColor",shadowColor); - this.shader.setValueFloat("inShadowBias",this.lightArray.shadowLight.shadowBias); - this.shader.setValueInt("inCastShadows",this.lightArray.shadowLight.castShadows); - - this.shader.setVector4Ptr('inLightAmbient',this.lightArray.ambient); - this.shader.setVector4Ptr('inLightDiffuse',this.lightArray.diffuse); - this.shader.setVector4Ptr('inLightSpecular',this.lightArray.specular); - this.shader.setValueIntPtr('inLightType',this.lightArray.type); - this.shader.setVector3Ptr('inLightAttenuation',this.lightArray.attenuation); - this.shader.setValueFloatPtr('inLightCutoffDistance',this.lightArray.cutoffDistance); - - // TODO: promote this value to a variable - let lightEmissionFactor = 10; - this.shader.setValueFloat('inLightEmissionFactor',lightEmissionFactor); - - this.shader.setTexture('inCubeMap',bg.scene.Cubemap.Current(this.context),bg.base.TextureUnit.TEXTURE_6); - - this.shader.setVector3Ptr('inLightDirection',this.lightArray.direction); - this.shader.setVector3Ptr('inLightPosition',this.lightArray.position); - this.shader.setValueFloatPtr('inSpotCutoff',this.lightArray.spotCutoff); - this.shader.setValueFloatPtr('inSpotExponent',this.lightArray.spotExponent); - - this.shader.setValueInt('inNumLights',this.lightArray.numLights); - } - else { - let BLACK = bg.Color.Black(); - this.shader.setVector4Ptr('inLightAmbient',BLACK.toArray()); - this.shader.setVector4Ptr('inLightDiffuse',BLACK.toArray()); - this.shader.setVector4Ptr('inLightSpecular',BLACK.toArray()); - this.shader.setVector3Ptr('inLightDirection',(new bg.Vector3(0,0,0)).toArray()); - this.shader.setValueInt('inNumLights',0); - } - - this.colorCorrection.apply(this.shader); - } - - setupVars() { - if (this.material) { - // Matrix state - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - this.shader.setMatrix4('inModelMatrix',matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',viewMatrix); - this.shader.setMatrix4('inProjectionMatrix',matrixState.projectionMatrixStack.matrixConst); - this.shader.setMatrix4('inNormalMatrix',matrixState.normalMatrix); - this.shader.setMatrix4('inViewMatrixInv',matrixState.viewMatrixInvert); - - // Material - // Prepare textures - let whiteTex = bg.base.TextureCache.WhiteTexture(this.context); - let blackTex = bg.base.TextureCache.BlackTexture(this.context); - let normalTex = bg.base.TextureCache.NormalTexture(this.context); - let texture = this.material.texture || whiteTex; - let lightMap = this.material.lightmap || whiteTex; - let normalMap = this.material.normalMap || normalTex; - let shininessMask = this.material.shininessMask || whiteTex; - let lightEmissionMask = this.material.lightEmissionMask || whiteTex; - - this.shader.setVector4('inDiffuseColor',this.material.diffuse); - this.shader.setVector4('inSpecularColor',this.material.specular); - this.shader.setValueFloat('inShininess',this.material.shininess); - this.shader.setTexture('inShininessMask',shininessMask,bg.base.TextureUnit.TEXTURE_3); - this.shader.setVector4('inShininessMaskChannel',this.material.shininessMaskChannelVector); - this.shader.setValueInt('inShininessMaskInvert',this.material.shininessMaskInvert); - this.shader.setValueFloat('inLightEmission',this.material.lightEmission); - this.shader.setTexture('inLightEmissionMask',lightEmissionMask,bg.base.TextureUnit.TEXTURE_4); - this.shader.setVector4('inLightEmissionMaskChannel',this.material.lightEmissionMaskChannelVector); - this.shader.setValueInt('inLightEmissionMaskInvert',this.material.lightEmissionMaskInvert); - this.shader.setValueFloat('inAlphaCutoff',this.material.alphaCutoff); - - this.shader.setTexture('inTexture',texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2('inTextureOffset',this.material.textureOffset); - this.shader.setVector2('inTextureScale',this.material.textureScale); - - this.shader.setTexture('inLightMap',lightMap,bg.base.TextureUnit.TEXTURE_1); - this.shader.setVector2('inLightMapOffset',this.material.lightmapOffset); - this.shader.setVector2('inLightMapScale',this.material.lightmapScale); - - this.shader.setTexture('inNormalMap',normalMap,bg.base.TextureUnit.TEXTURE_2); - this.shader.setVector2('inNormalMapScale',this.material.normalMapScale); - this.shader.setVector2('inNormalMapOffset',this.material.normalMapOffset); - - this.shader.setValueInt('inReceiveShadows',this.material.receiveShadows); - - let reflectionMask = this.material.reflectionMask || whiteTex; - this.shader.setValueFloat('inReflection',this.material.reflectionAmount); - this.shader.setTexture('inReflectionMask',reflectionMask,bg.base.TextureUnit.TEXTURE_7); - this.shader.setVector4('inReflectionMaskChannel',this.material.reflectionMaskChannelVector); - this.shader.setValueInt('inReflectionMaskInvert',this.material.reflectionMaskInvert); - - let roughnessMask = this.material.roughnessMask || whiteTex; - this.shader.setValueFloat('inRoughness',this.material.roughness); - if (this.context.getParameter(this.context.MAX_TEXTURE_IMAGE_UNITS)<9) { - this.shader.setTexture('inRoughnessMask',roughnessMask,bg.base.TextureUnit.TEXTURE_7); - } - else { - this.shader.setTexture('inRoughnessMask',roughnessMask,bg.base.TextureUnit.TEXTURE_8); - } - this.shader.setVector4('inRoughnessMaskChannel',this.material.roughnessMaskChannelVector); - this.shader.setValueInt('inRoughnessMaskInvert',this.material.roughnessMaskInvert); - - // Other settings - this.shader.setValueInt('inSelectMode',false); - - this.shader.setValueInt('inUnlit',this.material.unlit); - } - } - - } - - bg.base.ForwardEffect = ForwardEffect; - - // Define the maximum number of lights that can be used in forward render - bg.base.MAX_FORWARD_LIGHTS = 4; - -})(); - -(function() { - - bg.base.LightType = { - DIRECTIONAL: 4, - SPOT: 1, - POINT: 5, - DISABLED: 10 - }; - - class Light extends bg.app.ContextObject { - constructor(context) { - super(context); - - this._enabled = true; - - this._type = bg.base.LightType.DIRECTIONAL; - - this._direction = new bg.Vector3(0,0,-1); - - this._ambient = new bg.Color(0.2,0.2,0.2,1); - this._diffuse = new bg.Color(0.9,0.9,0.9,1); - this._specular = bg.Color.White(); - this._attenuation = new bg.Vector3(1,0.5,0.1); - this._spotCutoff = 20; - this._spotExponent = 30; - this._shadowStrength = 0.7; - this._cutoffDistance = -1; - this._castShadows = true; - this._shadowBias = 0.00002; - - this._projection = bg.Matrix4.Ortho(-10,10,-10,10,0.5,300.0); - } - - // If context is null, it will be used the same context as this light - clone(context) { - let newLight = new bg.base.Light(context || this.context); - newLight.assign(this); - return newLight; - } - - assign(other) { - this.enabled = other.enabled; - this.type = other.type; - this.direction.assign(other.direction); - this.ambient.assign(other.ambient); - this.diffuse.assign(other.diffuse); - this.specular.assign(other.specular); - this._attenuation.assign(other._attenuation); - this.spotCutoff = other.spotCutoff; - this.spotExponent = other.spotExponent; - this.shadowStrength = other.shadowStrength; - this.cutoffDistance = other.cutoffDistance; - this.castShadows = other.castShadows; - this.shadowBias = other.shadowBias; - } - - get enabled() { return this._enabled; } - set enabled(v) { this._enabled = v; } - - get type() { return this._type; } - set type(t) { this._type = t; } - - get direction() { return this._direction; } - set direction(d) { this._direction = d; } - - get ambient() { return this._ambient; } - set ambient(a) { this._ambient = a; } - get diffuse() { return this._diffuse; } - set diffuse(d) { this._diffuse = d; } - get specular() { return this._specular; } - set specular(s) { this._specular = s; } - - get attenuationVector() { return this._attenuation; } - get constantAttenuation() { return this._attenuation.x; } - get linearAttenuation() { return this._attenuation.y; } - get quadraticAttenuation() { return this._attenuation.z; } - set attenuationVector(a) { this._attenuation = a; } - set constantAttenuation(a) { this._attenuation.x = a; } - set linearAttenuation(a) { this._attenuation.y = a; } - set quadraticAttenuation(a) { this._attenuation.z = a; } - - get cutoffDistance() { return this._cutoffDistance; } - set cutoffDistance(c) { this._cutoffDistance = c; } - - get spotCutoff() { return this._spotCutoff; } - set spotCutoff(c) { this._spotCutoff = c; } - get spotExponent() { return this._spotExponent; } - set spotExponent(e) { this._spotExponent = e; } - - get shadowStrength() { return this._shadowStrength; } - set shadowStrength(s) { this._shadowStrength = s; } - get castShadows() { return this._castShadows; } - set castShadows(s) { this._castShadows = s; } - get shadowBias() { return this._shadowBias; } - set shadowBias(s) { this._shadowBias = s; } - - get projection() { return this._projection; } - set projection(p) { this._projection = p; } - - deserialize(sceneData) { - switch (sceneData.lightType) { - case 'kTypeDirectional': - this._type = bg.base.LightType.DIRECTIONAL; - // Use the predefined shadow bias for directional lights - //this._shadowBias = sceneData.shadowBias; - break; - case 'kTypeSpot': - this._type = bg.base.LightType.SPOT; - this._shadowBias = sceneData.shadowBias; - break; - case 'kTypePoint': - this._type = bg.base.LightType.POINT; - break; - } - - this._ambient = new bg.Color(sceneData.ambient); - this._diffuse = new bg.Color(sceneData.diffuse); - this._specular = new bg.Color(sceneData.specular); - this._attenuation = new bg.Vector3( - sceneData.constantAtt, - sceneData.linearAtt, - sceneData.expAtt - ); - this._spotCutoff = sceneData.spotCutoff || 20; - this._spotExponent = sceneData.spotExponent || 30; - this._shadowStrength = sceneData.shadowStrength; - this._cutoffDistance = sceneData.cutoffDistance; - this._projection = new bg.Matrix4(sceneData.projection); - this._castShadows = sceneData.castShadows; - } - - serialize(sceneData) { - let lightTypes = []; - lightTypes[bg.base.LightType.DIRECTIONAL] = "kTypeDirectional"; - lightTypes[bg.base.LightType.SPOT] = "kTypeSpot"; - lightTypes[bg.base.LightType.POINT] = "kTypePoint"; - sceneData.lightType = lightTypes[this._type]; - sceneData.ambient = this._ambient.toArray(); - sceneData.diffuse = this._diffuse.toArray(); - sceneData.specular = this._specular.toArray(); - sceneData.intensity = 1; - sceneData.constantAtt = this._attenuation.x; - sceneData.linearAtt = this._attenuation.y; - sceneData.expAtt = this._attenuation.z; - sceneData.spotCutoff = this._spotCutoff || 20; - sceneData.spotExponent = this._spotExponent || 30; - sceneData.shadowStrength = this._shadowStrength; - sceneData.cutoffDistance = this._cutoffDistance; - sceneData.projection = this._projection.toArray(); - sceneData.castShadows = this._castShadows; - sceneData.shadowBias = this._shadowBias || 0.0029; - } - } - - bg.base.Light = Light; - - // Store a light array, optimized to be used as shader input - class LightArray { - constructor() { - this.reset(); - } - - get type() { return this._type; } - get ambient() { return this._ambient; } - get diffuse() { return this._diffuse; } - get specular() { return this._specular; } - get position() { return this._position; } - get direction() { return this._direction; } - get rawDirection() { return this._rawDirection; } - get attenuation() { return this._attenuation; } - get spotCutoff() { return this._spotCutoff; } - get spotExponent() { return this._spotExponent; } - get shadowStrength() { return this._shadowStrength; } - get cutoffDistance() { return this._cutoffDistance; } - get numLights() { return this._numLights; } - - get lightTransform() { return this._lightTransform; } - - get shadowLight() { return this._shadowLight || { - shadowStrength: 0, - shadowColor: bg.Color.Black(), - shadowBias: 0, - castShadows: false, - projection: bg.Matrix4.Identity() - }} - get shadowLightTransform() { return this._shadowLightTransform || bg.Matrix4.Identity(); } - get shadowLightIndex() { return this._shadowLightIndex; } - - reset() { - this._type = []; - this._ambient = []; - this._diffuse = []; - this._specular = []; - this._position = []; - this._direction = []; - this._rawDirection = []; - this._attenuation = []; - this._spotCutoff = []; - this._spotExponent = []; - this._shadowStrength = []; - this._cutoffDistance = []; - this._numLights = 0; - this._lightTransform = []; - - // Forward render only supports one shadow map, so will only store - // one projection - this._shadowLightTransform = null; - this._shadowLightIndex = -1; - this._shadowLight = null; - } - - push(light,lightTransform) { - if (this._numLights==bg.base.MAX_FORWARD_LIGHTS) { - return false; - } - else { - if (this._shadowLightIndex==-1 && light.type!=bg.base.LightType.POINT && light.castShadows) { - this._shadowLightTransform = lightTransform; - this._shadowLight = light; - this._shadowLightIndex = this._numLights; - } - this._type.push(light.type); - this._ambient.push(...(light.ambient.toArray())); - this._diffuse.push(...(light.diffuse.toArray())); - this._specular.push(...(light.specular.toArray())); - this._rawDirection.push(light.direction); - this._attenuation.push(light.constantAttenuation); - this._attenuation.push(light.linearAttenuation); - this._attenuation.push(light.quadraticAttenuation); - this._spotCutoff.push(light.spotCutoff); - this._spotExponent.push(light.spotExponent); - this._shadowStrength.push(light.shadowStrength); - this._cutoffDistance.push(light.cutoffDistance); - - this._numLights++; - this._lightTransform.push(lightTransform); - return true; - } - } - - updatePositionAndDirection(viewMatrix) { - this._direction = []; - this._position = []; - for (let i=0; i { - if (!texData) { - resolve(); - } - else if (/data\:image\/[a-z]+\;base64\,/.test(texData)) { - let hash = bg.utils.md5(texData); - if (g_base64Images[hash]) { - mat[property] = g_base64Images[hash]; - } - else { - mat[property] = bg.base.Texture.FromBase64Image(context,texData); - g_base64Images[hash] = mat[property]; - } - resolve(mat[property]); - } -// else if (/data\:md5/.test(texData)) { - -// } - else { - let fullPath = basePath + texData; // TODO: add full path - bg.base.Loader.Load(context,fullPath) - .then(function(tex) { - mat[property] = tex; - resolve(tex); - }); - } - }); - } - - class Material { - // Create and initialize a material from the json material definition - static FromMaterialDefinition(context,def,basePath="") { - return new Promise((resolve,reject) => { - let mat = new Material(); - - mat.diffuse = readVector(def.diffuse) || bg.Color.White(); - mat.specular = readVector(def.specular) || bg.Color.White(); - mat.shininess = def.shininess || 0; - mat.shininessMaskChannel = def.shininessMaskChannel || 0; - mat.shininessMaskInvert = def.shininessMaskInvert || false; - mat.lightEmission = def.lightEmission || 0; - mat.lightEmissionMaskChannel = def.lightEmissionMaskChannel || 0; - mat.lightEmissionMaskInvert = def.lightEmissionMaskInvert || false; - mat.refractionAmount = def.refractionAmount || 0; - mat.reflectionAmount = def.reflectionAmount || 0; - mat.reflectionMaskChannel = def.reflectionMaskChannel || 0; - mat.reflectionMaskInvert = def.reflectionMaskInvert || false; - mat.textureOffset = readVector(def.textureOffset) || new bg.Vector2(0,0); - mat.textureScale = readVector(def.textureScale) || new bg.Vector2(1,1); - mat.normalMapOffset = readVector(def.normalMapOffset) || new bg.Vector2(0,0); - mat.normalMapScale = readVector(def.normalMapScale) || new bg.Vector2(1,1); - mat.cullFace = def.cullFace===undefined ? true : def.cullFace; - mat.castShadows = def.castShadows===undefined ? true : def.castShadows; - mat.receiveShadows = def.receiveShadows===undefined ? true : def.receiveShadows; - mat.alphaCutoff = def.alphaCutoff===undefined ? 0.5 : def.alphaCutoff; - mat.name = def.name; - mat.description = def.description; - mat.roughness = def.roughness || 0; - mat.roughnessMaskChannel = def.roughnessMaskChannel || 0; - mat.roughnessMaskInvert = def.roughnessMaskInvert || false; - mat.unlit = def.unlit || false; - - let texPromises = []; - texPromises.push(readTexture(context,basePath,def.shininessMask,mat,"shininessMask")); - texPromises.push(readTexture(context,basePath,def.lightEmissionMask,mat,"lightEmissionMask")); - texPromises.push(readTexture(context,basePath,def.reflectionMask,mat,"reflectionMask")); - texPromises.push(readTexture(context,basePath,def.texture,mat,"texture")); - texPromises.push(readTexture(context,basePath,def.normalMap,mat,"normalMap")); - texPromises.push(readTexture(context,basePath,def.roughnessMask,mat,"roughnessMask")); - - Promise.all(texPromises) - .then(() => { - resolve(mat); - }); - }); - } - - constructor() { - this._diffuse = bg.Color.White(); - this._specular = bg.Color.White(); - this._shininess = 0; - this._lightEmission = 0; - this._refractionAmount = 0; - this._reflectionAmount = 0; - this._texture = null; - this._lightmap = null; - this._normalMap = null; - this._textureOffset = new bg.Vector2(); - this._textureScale = new bg.Vector2(1); - this._lightmapOffset = new bg.Vector2(); - this._lightmapScale = new bg.Vector2(1); - this._normalMapOffset = new bg.Vector2(); - this._normalMapScale = new bg.Vector2(1); - this._castShadows = true; - this._receiveShadows = true; - this._alphaCutoff = 0.5; - this._shininessMask = null; - this._shininessMaskChannel = 0; - this._shininessMaskInvert = false; - this._lightEmissionMask = null; - this._lightEmissionMaskChannel = 0; - this._lightEmissionMaskInvert = false; - this._reflectionMask = null; - this._reflectionMaskChannel = 0; - this._reflectionMaskInvert = false; - this._cullFace = true; - this._roughness = 0; - this._roughnessMask = null; - this._roughnessMaskChannel = 0; - this._roughnessMaskInvert = false; - this._unlit = false; - - this._selectMode = false; - } - - clone() { - let copy = new Material(); - copy.assign(this); - return copy; - } - - assign(other) { - this._diffuse = new bg.Color(other.diffuse); - this._specular = new bg.Color(other.specular); - this._shininess = other.shininess; - this._lightEmission = other.lightEmission; - this._refractionAmount = other.refractionAmount; - this._reflectionAmount = other.reflectionAmount; - this._texture = other.texture; - this._lightmap = other.lightmap; - this._normalMap = other.normalMap; - this._textureOffset = new bg.Vector2(other.textureOffset); - this._textureScale = new bg.Vector2(other.textureScale); - this._lightmapOffset = new bg.Vector2(other.ligthmapOffset); - this._lightmapScale = new bg.Vector2(other.lightmapScale); - this._normalMapOffset = new bg.Vector2(other.normalMapOffset); - this._normalMapScale = new bg.Vector2(other.normalMapScale); - this._castShadows = other.castShadows; - this._receiveShadows = other.receiveShadows; - this._alphaCutoff = other.alphaCutoff; - this._shininessMask = other.shininessMask; - this._shininessMaskChannel = other.shininessMaskChannel; - this._shininessMaskInvert = other.shininessMaskInvert; - this._lightEmissionMask = other.lightEmissionMask; - this._lightEmissionMaskChannel = other.lightEmissionMaskChannel; - this._lightEmissionMaskInvert = other.lightEmissionMaskInvert; - this._reflectionMask = other.reflectionMask; - this._reflectionMaskChannel = other.reflectionMaskChannel; - this._reflectionMaskInvert = other.reflectionMaskInvert; - this._cullFace = other.cullFace; - this._roughness = other.roughness; - this._roughnessMask = other.roughnessMask; - this._roughnessMaskChannel = other.roughnessMaskChannel; - this._roughnessMaskInvert = other.roughnessMaskInvert; - this._unlit = other.unlit; - } - - get isTransparent() { - return this._diffuse.a<1; - } - - get diffuse() { return this._diffuse; } - get specular() { return this._specular; } - get shininess() { return this._shininess; } - get lightEmission() { return this._lightEmission; } - get refractionAmount() { return this._refractionAmount; } - get reflectionAmount() { return this._reflectionAmount; } - get texture() { return this._texture; } - get lightmap() { return this._lightmap; } - get normalMap() { return this._normalMap; } - get textureOffset() { return this._textureOffset; } - get textureScale() { return this._textureScale; } - get lightmapOffset() { return this._lightmapOffset; } - get lightmapScale() { return this._lightmapScale; } - get normalMapOffset() { return this._normalMapOffset; } - get normalMapScale() { return this._normalMapScale; } - get castShadows() { return this._castShadows; } - get receiveShadows() { return this._receiveShadows; } - get alphaCutoff() { return this._alphaCutoff; } - get shininessMask() { return this._shininessMask; } - get shininessMaskChannel() { return this._shininessMaskChannel; } - get shininessMaskInvert() { return this._shininessMaskInvert; } - get lightEmissionMask() { return this._lightEmissionMask; } - get lightEmissionMaskChannel() { return this._lightEmissionMaskChannel; } - get lightEmissionMaskInvert() { return this._lightEmissionMaskInvert; } - get reflectionMask() { return this._reflectionMask; } - get reflectionMaskChannel() { return this._reflectionMaskChannel; } - get reflectionMaskInvert() { return this._reflectionMaskInvert; } - get cullFace() { return this._cullFace; } - get roughness() { return this._roughness; } - get roughnessMask() { return this._roughnessMask; } - get roughnessMaskChannel() { return this._roughnessMaskChannel; } - get roughnessMaskInvert() { return this._roughnessMaskInvert; } - get unlit() { return this._unlit; } - - - set diffuse(newVal) { this._diffuse = newVal; } - set specular(newVal) { this._specular = newVal; } - set shininess(newVal) { if (!isNaN(newVal)) this._shininess = newVal; } - set lightEmission(newVal) { if (!isNaN(newVal)) this._lightEmission = newVal; } - set refractionAmount(newVal) { this._refractionAmount = newVal; } - set reflectionAmount(newVal) { this._reflectionAmount = newVal; } - set texture(newVal) { this._texture = newVal; } - set lightmap(newVal) { this._lightmap = newVal; } - set normalMap(newVal) { this._normalMap = newVal; } - set textureOffset(newVal) { this._textureOffset = newVal; } - set textureScale(newVal) { this._textureScale = newVal; } - set lightmapOffset(newVal) { this._lightmapOffset = newVal; } - set lightmapScale(newVal) { this._lightmapScale = newVal; } - set normalMapOffset(newVal) { this._normalMapOffset = newVal; } - set normalMapScale(newVal) { this._normalMapScale = newVal; } - set castShadows(newVal) { this._castShadows = newVal; } - set receiveShadows(newVal) { this._receiveShadows = newVal; } - set alphaCutoff(newVal) { if (!isNaN(newVal)) this._alphaCutoff = newVal; } - set shininessMask(newVal) { this._shininessMask = newVal; } - set shininessMaskChannel(newVal) { this._shininessMaskChannel = newVal; } - set shininessMaskInvert(newVal) { this._shininessMaskInvert = newVal; } - set lightEmissionMask(newVal) { this._lightEmissionMask = newVal; } - set lightEmissionMaskChannel(newVal) { this._lightEmissionMaskChannel = newVal; } - set lightEmissionMaskInvert(newVal) { this._lightEmissionMaskInvert = newVal; } - set reflectionMask(newVal) { this._reflectionMask = newVal; } - set reflectionMaskChannel(newVal) { this._reflectionMaskChannel = newVal; } - set reflectionMaskInvert(newVal) { this._reflectionMaskInvert = newVal; } - set cullFace(newVal) { this._cullFace = newVal; } - set roughness(newVal) { this._roughness = newVal; } - set roughnessMask(newVal) { this._roughnessMask = newVal; } - set roughnessMaskChannel(newVal) { this._roughnessMaskChannel = newVal; } - set roughnessMaskInvert(newVal) { this._roughnessMaskInvert = newVal; } - - get unlit() { return this._unlit; } - set unlit(u) { this._unlit = u; } - - get selectMode() { return this._selectMode; } - set selectMode(s) { this._selectMode = s; } - - // Mask channel vectors: used to pass the mask channel to a shader - get lightEmissionMaskChannelVector() { - return channelVector(this.lightEmissionMaskChannel) - } - - get shininessMaskChannelVector() { - return channelVector(this.shininessMaskChannel); - } - - get reflectionMaskChannelVector() { - return channelVector(this.reflectionMaskChannel); - } - - get roughnessMaskChannelVector() { - return channelVector(this.roughnessMaskChannel); - } - - // Returns an array of the external resources used by this material, for example, - // the paths to the textures. If the "resources" parameter (array) is passed, the resources - // will be added to this array, and the parameter will be modified to include the new - // resources. If a resource exists in the "resources" parameter, it will not be added - getExternalResources(resources=[]) { - function tryadd(texture) { - if (texture && texture.fileName && texture.fileName!="" && resources.indexOf(texture.fileName)==-1) { - resources.push(texture.fileName); - } - } - tryadd(this.texture); - tryadd(this.lightmap); - tryadd(this.normalMap); - tryadd(this.shininessMask); - tryadd(this.lightEmissionMask); - tryadd(this.reflectionMask); - tryadd(this.roughnessMask); - return resources; - } - - copyMaterialSettings(mat,mask) { - if ( mask & bg.base.MaterialFlag.DIFFUSE) { - mat.diffuse = this.diffuse; - } - if ( mask & bg.base.MaterialFlag.SPECULAR) { - mat.specular = this.specular; - } - if ( mask & bg.base.MaterialFlag.SHININESS) { - mat.shininess = this.shininess; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION) { - mat.lightEmission = this.lightEmission; - } - if ( mask & bg.base.MaterialFlag.REFRACTION_AMOUNT) { - mat.refractionAmount = this.refractionAmount; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_AMOUNT) { - mat.reflectionAmount = this.reflectionAmount; - } - if ( mask & bg.base.MaterialFlag.TEXTURE) { - mat.texture = this.texture; - } - if ( mask & bg.base.MaterialFlag.LIGHT_MAP) { - mat.lightmap = this.lightmap; - } - if ( mask & bg.base.MaterialFlag.NORMAL_MAP) { - mat.normalMap = this.normalMap; - } - if ( mask & bg.base.MaterialFlag.TEXTURE_OFFSET) { - mat.textureOffset = this.textureOffset; - } - if ( mask & bg.base.MaterialFlag.TEXTURE_SCALE) { - mat.textureScale = this.textureScale; - } - if ( mask & bg.base.MaterialFlag.LIGHT_MAP_OFFSET) { - mat.lightmapOffset = this.lightmapOffset; - } - if ( mask & bg.base.MaterialFlag.LIGHT_MAP_SCALE) { - mat.lightmapScale = this.lightmapScale; - } - if ( mask & bg.base.MaterialFlag.NORMAL_MAP_OFFSET) { - mat.normalMapOffset = this.normalMapOffset; - } - if ( mask & bg.base.MaterialFlag.NORMAL_MAP_SCALE) { - mat.normalMapScale = this.normalMapScale; - } - if ( mask & bg.base.MaterialFlag.CAST_SHADOWS) { - mat.castShadows = this.castShadows; - } - if ( mask & bg.base.MaterialFlag.RECEIVE_SHADOWS) { - mat.receiveShadows = this.receiveShadows; - } - if ( mask & bg.base.MaterialFlag.ALPHA_CUTOFF) { - mat.alphaCutoff = this.alphaCutoff; - } - if ( mask & bg.base.MaterialFlag.SHININESS_MASK) { - mat.shininessMask = this.shininessMask; - } - if ( mask & bg.base.MaterialFlag.SHININESS_MASK_CHANNEL) { - mat.shininessMaskChannel = this.shininessMaskChannel; - } - if ( mask & bg.base.MaterialFlag.SHININESS_MASK_INVERT) { - mat.shininessMaskInvert = this.shininessMaskInvert; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION_MASK) { - mat.lightEmissionMask = this.lightEmissionMask; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION_MASK_CHANNEL) { - mat.lightEmissionMaskChannel = this.lightEmissionMaskChannel; - } - if ( mask & bg.base.MaterialFlag.LIGHT_EMISSION_MASK_INVERT) { - mat.lightEmissionMaskInvert = this.lightEmissionMaskInvert; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_MASK) { - mat.reflectionMask = this.reflectionMask; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_MASK_CHANNEL) { - mat.reflectionMaskChannel = this.reflectionMaskChannel; - } - if ( mask & bg.base.MaterialFlag.REFLECTION_MASK_INVERT) { - mat.reflectionMaskInvert = this.reflectionMaskInvert; - } - if ( mask & bg.base.MaterialFlag.CULL_FACE) { - mat.cullFace = this.cullFace; - } - - // All the roughness attributes are copied together using this flag. In - // the future, the *_MASK, *_MASK_CHANNEL and *_MASK_INVERT for shininess, - // light emission and reflection, will be deprecated and will work in the - // same way as ROUGHNESS here - if ( mask & bg.base.MaterialFlag.ROUGHNESS) { - mat.reflectionAmount = this.reflectionAmount; - mat.reflectionMask = this.reflectionMask; - mat.reflectionMaskChannel = this.reflectionMaskChannel; - mat.reflectionMaskInvert = this.reflectionMaskInvert; - } - - if (mask & bg.base.MaterialFlag.UNLIT) { - mat.unlit = this.unlit; - } - } - - applyModifier(context, mod, resourcePath) { - if (mod.isEnabled(bg.base.MaterialFlag.DIFFUSE)) { - this.diffuse = mod.diffuse; - } - if (mod.isEnabled(bg.base.MaterialFlag.SPECULAR)) { - this.specular = mod.specular; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS)) { - this.shininess = mod.shininess; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION)) { - this.lightEmission = mod.lightEmission; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFRACTION_AMOUNT)) { - this.refractionAmount = mod.refractionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_AMOUNT)) { - this.reflectionAmount = mod.reflectionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE)) { - this.texture = getTexture(context,mod.texture,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP)) { - this.lightmap = getTexture(context,mod.lightmap,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP)) { - this.normalMap = getTexture(context,mod.normalMap,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_OFFSET)) { - this.textureOffset = mod.textureOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_SCALE)) { - this.textureScale = mod.textureScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_OFFSET)) { - this.lightmapOffset = mod.lightmapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_SCALE)) { - this.lightmapScale = mod.lightmapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_OFFSET)) { - this.normalMapOffset = mod.normalMapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_SCALE)) { - this.normalMapScale = mod.normalMapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.CAST_SHADOWS)) { - this.castShadows = mod.castShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.RECEIVE_SHADOWS)) { - this.receiveShadows = mod.receiveShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.ALPHA_CUTOFF)) { - this.alphaCutoff = mod.alphaCutoff; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK)) { - this.shininessMask = getTexture(context,mod.shininessMask,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_CHANNEL)) { - this.shininessMaskChannel = mod.shininessMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_INVERT)) { - this.shininessMaskInvert = mod.shininessMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK)) { - this.lightEmissionMask = getTexture(context,mod.lightEmissionMask,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_CHANNEL)) { - this.lightEmissionMaskChannel = mod.lightEmissionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_INVERT)) { - this.lightEmissionMaskInvert = mod.lightEmissionMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK)) { - this.reflectionMask = getTexture(context,mod.reflectionMask,resourcePath); - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_CHANNEL)) { - this.reflectionMaskChannel = mod.reflectionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_INVERT)) { - this.reflectionMaskInvert = mod.reflectionMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.CULL_FACE)) { - this.cullFace = mod.cullFace; - } - - // See above note for ROUGHNESS flags - if (mod.isEnabled(bg.base.MaterialFlag.ROUGHNESS)) { - this.roughness = mod.roughness; - this.roughnessMask = getTexture(context,mod.roughnessMask,resourcePath); - this.roughnessMaskChannel = mod.roughnessMaskChannel; - this.roughnessMaskInvert = mod.roughnessMaskInvert; - } - - if (mod.isEnabled(bg.base.MaterialFlag.UNLIT)) { - this.unlit = mod.unlit; - } - } - - getModifierWithMask(modifierMask) { - var mod = new MaterialModifier(); - - mod.modifierFlags = modifierMask; - - if (mod.isEnabled(bg.base.MaterialFlag.DIFFUSE)) { - mod.diffuse = this.diffuse; - } - if (mod.isEnabled(bg.base.MaterialFlag.SPECULAR)) { - mod.specular = this.specular; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS)) { - mod.shininess = this.shininess; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION)) { - mod.lightEmission = this.lightEmission; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFRACTION_AMOUNT)) { - mod.refractionAmount = this.refractionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_AMOUNT)) { - mod.reflectionAmount = this.reflectionAmount; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE)) { - mod.texture = getPath(this.texture); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP)) { - mod.lightmap = getPath(this.lightmap); - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP)) { - mod.normalMap = getPath(this.normalMap); - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_OFFSET)) { - mod.textureOffset = this.textureOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.TEXTURE_SCALE)) { - mod.textureScale = this.textureScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_OFFSET)) { - mod.lightmapOffset = this.lightmapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_MAP_SCALE)) { - mod.lightmapScale = this.lightmapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_OFFSET)) { - mod.normalMapOffset = this.normalMapOffset; - } - if (mod.isEnabled(bg.base.MaterialFlag.NORMAL_MAP_SCALE)) { - mod.normalMapScale = this.normalMapScale; - } - if (mod.isEnabled(bg.base.MaterialFlag.CAST_SHADOWS)) { - mod.castShadows = this.castShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.RECEIVE_SHADOWS)) { - mod.receiveShadows = this.receiveShadows; - } - if (mod.isEnabled(bg.base.MaterialFlag.ALPHA_CUTOFF)) { - mod.alphaCutoff = this.alphaCutoff; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK)) { - mod.shininessMask = getPath(this.shininessMask); - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_CHANNEL)) { - mod.shininessMaskChannel = this.shininessMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.SHININESS_MASK_INVERT)) { - mod.shininessMaskInvert = this.shininessMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK)) { - mod.lightEmissionMask = getPath(this.lightEmissionMask); - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_CHANNEL)) { - mod.lightEmissionMaskChannel = this.lightEmissionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.LIGHT_EMISSION_MASK_INVERT)) { - mod.lightEmissionMaskInver = this.lightEmissionMaskInver; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK)) { - mod.reflectionMask = getPath(this.reflectionMask); - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_CHANNEL)) { - mod.reflectionMaskChannel = this.reflectionMaskChannel; - } - if (mod.isEnabled(bg.base.MaterialFlag.REFLECTION_MASK_INVERT)) { - mod.reflectionMaskInvert = this.reflectionMaskInvert; - } - if (mod.isEnabled(bg.base.MaterialFlag.CULL_FACE)) { - mod.cullFace = this.cullFace; - } - - // See above note about ROUGHNESS flag - if (mod.isEnabled(bg.base.MaterialFlag.ROUGHNESS)) { - mod.roughness = this.roughness; - mod.roughnessMask = getPath(this.roughnessMask); - mod.roughnessMaskChannel = this.roughnessMaskChannel; - mod.roughnessMaskInvert = this.roughnessMaskInvert; - } - - if (mod.isEnabled(bg.base.MaterialFlag.UNLIT)) { - mod.unlit = this.unlit; - } - - return mod; - } - - static GetMaterialWithJson(context,data,path) { - let material = new Material(); - if (data.cullFace===undefined) { - data.cullFace = true; - } - - material.diffuse.set(data.diffuseR,data.diffuseG,data.diffuseB,data.diffuseA); - material.specular.set(data.specularR,data.specularG,data.specularB,data.specularA); - material.shininess = data.shininess; - material.lightEmission = data.lightEmission; - - material.refractionAmount = data.refractionAmount; - material.reflectionAmount = data.reflectionAmount; - - material.textureOffset.set(data.textureOffsetX,data.textureOffsetY); - material.textureScale.set(data.textureScaleX,data.textureScaleY); - - material.lightmapOffset.set(data.lightmapOffsetX,data.lightmapOffsetY); - material.lightmapScale.set(data.lightmapScaleX,data.lightmapScaleY); - - material.normalMapOffset.set(data.normalMapOffsetX,data.normalMapOffsetY); - material.normalMapScale.set(data.normalMapScaleX,data.normalMapScaleY); - - material.alphaCutoff = data.alphaCutoff; - material.castShadows = data.castShadows; - material.receiveShadows = data.receiveShadows; - - material.shininessMaskChannel = data.shininessMaskChannel; - material.shininessMaskInvert = data.invertShininessMask; - - material.lightEmissionMaskChannel = data.lightEmissionMaskChannel; - material.lightEmissionMaskInvert = data.invertLightEmissionMask; - - material.reflectionMaskChannel = data.reflectionMaskChannel; - material.reflectionMaskInvert = data.invertReflectionMask; - - material.roughness = data.roughness; - material.roughnessMaskChannel = data.roughnessMaskChannel; - material.roughnessMaskInvert = data.invertRoughnessMask; - - material.cullFace = data.cullFace; - - material.unlit = data.unlit; - - if (path && path[path.length-1]!='/') { - path += '/'; - } - - function mergePath(path,file) { - if (!file) return null; - return path ? path + file:file; - } - - data.texture = mergePath(path,data.texture); - data.lightmap = mergePath(path,data.lightmap); - data.normalMap = mergePath(path,data.normalMap); - data.shininessMask = mergePath(path,data.shininessMask); - data.lightEmissionMask = mergePath(path,data.lightEmissionMask); - data.reflectionMask = mergePath(path,data.reflectionMask); - data.roughnessMask = mergePath(path,data.roughnessMask); - - return new Promise((accept,reject) => { - let textures = []; - - if (data.texture) { - textures.push(data.texture); - } - if (data.lightmap && textures.indexOf(data.lightmap)==-1) { - textures.push(data.lightmap); - } - if (data.normalMap && textures.indexOf(data.normalMap)==-1) { - textures.push(data.normalMap); - } - if (data.shininessMask && textures.indexOf(data.shininessMask)==-1) { - textures.push(data.shininessMask); - } - if (data.lightEmissionMask && textures.indexOf(data.lightEmissionMask)==-1) { - textures.push(data.lightEmissionMask); - } - if (data.reflectionMask && textures.indexOf(data.reflectionMask)==-1) { - textures.push(data.reflectionMask); - } - if (data.roughnessMask && textures.indexOf(data.roughnessMask)==-1) { - textures.push(data.roughnessMask); - } - - bg.utils.Resource.Load(textures) - .then(function(images) { - material.texture = loadTexture(context,images[data.texture],data.texture); - material.lightmap = loadTexture(context,images[data.lightmap],data.lightmap); - material.normalMap = loadTexture(context,images[data.normalMap],data.normalMap); - material.shininessMask = loadTexture(context,images[data.shininessMask],data.shininessMask); - material.lightEmissionMask = loadTexture(context,images[data.lightEmissionMask],data.lightEmissionMask); - material.reflectionMask = loadTexture(context,images[data.reflectionMask],data.reflectionMask); - material.roughnessMask = loadTexture(context,images[data.roughnessMask],data.roughnessMask); - accept(material); - }); - }); - } - } - - bg.base.Material = Material; -})(); - -(function() { - class MatrixStack { - constructor() { - this._matrix = bg.Matrix4.Identity(); - this._stack = []; - this._changed = true; - } - - get changed() { return this._changed; } - set changed(c) { this._changed = c; } - - push() { - this._stack.push(new bg.Matrix4(this._matrix)); - } - - set(m) { - this._matrix.assign(m); - this._changed = true; - return this; - } - - mult(m) { - this._matrix.mult(m); - this._changed = true; - return this; - } - - identity() { - this._matrix.identity(); - this._changed = true; - return this; - } - - translate(x, y, z) { - this._matrix.translate(x, y, z); - this._changed = true; - return this; - } - - rotate(alpha, x, y, z) { - this._matrix.rotate(alpha, x, y, z); - this._changed = true; - return this; - } - - scale(x, y, z) { - this._matrix.scale(x, y, z); - this._changed = true; - return this; - } - - setScale(x, y, z) { - this._matrix.setScale(x,y,z); - this._changed = true; - return this; - } - - perspective(fov,aspect,near,far) { - this._matrix - .identity() - .perspective(fov,aspect,near,far); - this._changed = true; - return this; - } - - frustum(left, right, bottom, top, nearPlane, farPlane) { - this._matrix - .identity() - .frustum(left,right,bottom,top,nearPlane,farPlane); - this._changed = true; - return this; - } - - ortho(left, right, bottom, top, nearPlane, farPlane) { - this._matrix - .identity() - .ortho(left,right,bottom,top,nearPlane,farPlane); - this._changed = true; - return this; - } - - invert() { - this._matrix.invert(); - this._changed = true; - return this; - } - - get matrix() { - this._changed = true; - return this._matrix; - } - - // This accessor will return the current matrix without mark the internal state - // to changed. There isn't any way in JavaScript to ensure that the returned matrix - // will not be changed, therefore use this accessor carefully. It's recommended to use this - // accessor ONLY to retrieve the matrix and pass it to the shaders. - get matrixConst() { - return this._matrix; - } - - pop() { - if (this._stack.length) { - this._matrix.assign(this._stack.pop()); - this._changed = true; - } - return this._matrix; - } - } - - bg.base.MatrixStack = MatrixStack; - - let s_MatrixState = null; - - class MatrixState { - static Current() { - if (!s_MatrixState) { - s_MatrixState = new MatrixState(); - } - return s_MatrixState; - } - - static SetCurrent(s) { - s_MatrixState = s; - return s_MatrixState; - } - - constructor() { - // Matrixes - this._modelMatrixStack = new MatrixStack(); - this._viewMatrixStack = new MatrixStack(); - this._projectionMatrixStack = new MatrixStack(); - this._modelViewMatrix = bg.Matrix4.Identity(); - this._normalMatrix = bg.Matrix4.Identity(); - this._cameraDistanceScale = null; - } - - get modelMatrixStack() { - return this._modelMatrixStack; - } - - get viewMatrixStack() { - return this._viewMatrixStack; - } - - get projectionMatrixStack() { - return this._projectionMatrixStack; - } - - get modelViewMatrix() { - if (!this._modelViewMatrix || this._modelMatrixStack.changed || this._viewMatrixStack.changed) { - this._modelViewMatrix = new bg.Matrix4(this._viewMatrixStack._matrix); - this._modelViewMatrix.mult(this._modelMatrixStack._matrix); - this._modelMatrixStack.changed = false; - this._viewMatrixStack.changed = false; - } - return this._modelViewMatrix; - } - - get normalMatrix() { - if (!this._normalMatrix || this._modelMatrixStack.changed || this._viewMatrixStack.changed) { - this._normalMatrix = new bg.Matrix4(this.modelViewMatrix); - this._normalMatrix.invert(); - this._normalMatrix.traspose(); - this._modelMatrixStack.changed = false; - } - return this._normalMatrix; - } - - get viewMatrixInvert() { - if (!this._viewMatrixInvert || this._viewMatrixStack.changed) { - this._viewMatrixInvert = new bg.Matrix4(this.viewMatrixStack.matrixConst); - this._viewMatrixInvert.invert(); - } - return this._viewMatrixInvert; - } - - // This function returns a number that represents the - // distance from the camera to the model. - get cameraDistanceScale() { - return this._cameraDistanceScale = this._viewMatrixStack.matrix.position.magnitude(); - } - } - - bg.base.MatrixState = MatrixState; -})(); -(function() { - - bg.base.ClearBuffers = { - COLOR:null, - DEPTH:null, - COLOR_DEPTH:null - }; - - bg.base.BlendMode = { - NORMAL: 1, // It works as the Photoshop layers does GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA, GL_FUNC_ADD - MULTIPLY: 2, // GL_ZERO GL_SRC_COLOR, GL_FUNC_ADD - ADD: 3, // GL_ONE GL_ONE, GL_FUNC_ADD - SUBTRACT: 4, // GL_ONE GL_ONE, GL_FUNC_SUBTRACT - ALPHA_ADD: 5, // GL_SRC_ALPHA GL_DST_ALPHA, GL_FUNC_ADD - ALPHA_SUBTRACT: 6 // GL_SRC_ALPHA GL_DST_ALPHA, GL_FUNC_SUBTRACT - }; - - bg.base.OpacityLayer = { - TRANSPARENT: 0b1, - OPAQUE: 0b10, - GIZMOS: 0b100, - SELECTION: 0b1000, - GIZMOS_SELECTION: 0b10000, - ALL: 0b1111, - NONE: 0 - }; - - class PipelineImpl { - constructor(context) { - this.initFlags(context); - bg.base.ClearBuffers.COLOR_DEPTH = bg.base.ClearBuffers.COLOR | bg.base.ClearBuffers.DEPTH; - } - - initFlags(context) {} - - setViewport(context,vp) {} - clearBuffers(context,color,buffers) {} - setDepthTestEnabled(context,e) {} - setBlendEnabled(context,e) {} - setBlendMode(context,m) {} - setCullFace(context,e) {} - } - - bg.base.PipelineImpl = PipelineImpl; - - let s_currentPipeline = null; - - function enablePipeline(pipeline) { - if (pipeline._effect) { - pipeline._effect.setActive(); - } - pipeline.renderSurface.setActive(); - - bg.Engine.Get().pipeline.setViewport(pipeline.context,pipeline._viewport); - bg.Engine.Get().pipeline.setDepthTestEnabled(pipeline.context,pipeline._depthTest); - bg.Engine.Get().pipeline.setCullFace(pipeline.context,pipeline._cullFace); - bg.Engine.Get().pipeline.setBlendEnabled(pipeline.context,pipeline._blend); - bg.Engine.Get().pipeline.setBlendMode(pipeline.context,pipeline._blendMode); - } - - class Pipeline extends bg.app.ContextObject { - static SetCurrent(p) { - s_currentPipeline = p; - if (s_currentPipeline) { - enablePipeline(s_currentPipeline); - } - } - - static Current() { return s_currentPipeline; } - - constructor(context) { - super(context); - - // Opacity layer - this._opacityLayer = bg.base.OpacityLayer.ALL; - - // Viewport - this._viewport = new bg.Viewport(0,0,200,200); - - // Clear buffer - this._clearColor = bg.Color.Black(); - - // Effect (used with draw method) - this._effect = null; - - // Texture effect (used with drawTexture method) - this._textureEffect = null; - - - // Other flags - this._depthTest = true; - this._cullFace = true; - - // Render surface - this._renderSurface = null; - - // Blending - this._blend = false; - this._blendMode = bg.base.BlendMode.NORMAL; - - this._buffersToClear = bg.base.ClearBuffers.COLOR_DEPTH; - } - - get isCurrent() { return s_currentPipeline==this; } - - set opacityLayer(l) { this._opacityLayer = l; } - get opacityLayer() { return this._opacityLayer; } - shouldDraw(material) { - return material && - ((material.isTransparent && (this._opacityLayer & bg.base.OpacityLayer.TRANSPARENT)!=0) || - (!material.isTransparent && (this._opacityLayer & bg.base.OpacityLayer.OPAQUE)!=0)); - } - - get effect() { return this._effect; } - set effect(m) { - this._effect = m; - if (this._effect && this.isCurrent) { - this._effect.setActive(); - } - } - - get textureEffect() { - if (!this._textureEffect) { - this._textureEffect = new bg.base.DrawTextureEffect(this.context); - } - return this._textureEffect; - } - - set textureEffect(t) { - this._textureEffect = t; - } - - set buffersToClear(b) { this._buffersToClear = b; } - get buffersToClear() { return this._buffersToClear; } - - get renderSurface() { - if (!this._renderSurface) { - this._renderSurface = new bg.base.ColorSurface(this.context); - this._renderSurface.setActive(); - } - return this._renderSurface; - } - - set renderSurface(r) { - this._renderSurface = r; - if (this.isCurrent) { - this._renderSurface.setActive(); - } - } - - draw(polyList) { - if (this._effect && polyList && this.isCurrent) { - let cf = this.cullFace; - this._effect.bindPolyList(polyList); - if (this._effect.material) { - - this.cullFace = this._effect.material.cullFace; - } - polyList.draw(); - this._effect.unbind(); - this.cullFace = cf; - } - } - - drawTexture(texture) { - let depthTest = this.depthTest; - this.depthTest = false; - this.textureEffect.drawSurface(texture); - this.depthTest = depthTest; - } - - get blend() { return this._blend; } - set blend(b) { - this._blend = b; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setBlendEnabled(this.context,this._blend); - } - } - - get blendMode() { return this._blendMode; } - set blendMode(b) { - this._blendMode = b; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setBlendMode(this.context,this._blendMode); - } - } - - get viewport() { return this._viewport; } - set viewport(vp) { - this._viewport = vp; - if (this.renderSurface.resizeOnViewportChanged) { - this.renderSurface.size = new bg.Vector2(vp.width,vp.height); - } - if (this.isCurrent) { - bg.Engine.Get().pipeline.setViewport(this.context,this._viewport); - } - } - - clearBuffers(buffers) { - if (this.isCurrent) { - buffers = buffers!==undefined ? buffers : this._buffersToClear; - bg.Engine.Get().pipeline.clearBuffers(this.context,this._clearColor,buffers); - } - } - - get clearColor() { return this._clearColor; } - set clearColor(c) { this._clearColor = c; } - - get depthTest() { return this._depthTest; } - set depthTest(e) { - this._depthTest = e; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setDepthTestEnabled(this.context,this._depthTest); - } - } - - get cullFace() { return this._cullFace; } - set cullFace(c) { - this._cullFace = c; - if (this.isCurrent) { - bg.Engine.Get().pipeline.setCullFace(this.context,this._cullFace); - } - } - } - - bg.base.Pipeline = Pipeline; -})(); -(function() { - - bg.base.BufferType = { - VERTEX: 1 << 0, - NORMAL: 1 << 1, - TEX_COORD_0: 1 << 2, - TEX_COORD_1: 1 << 3, - TEX_COORD_2: 1 << 4, - COLOR: 1 << 5, - TANGENT: 1 << 6, - INDEX: 1 << 7 - }; - - class PolyListImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) {} - create(context) {} - build(context,plist,vert,norm,t0,t1,t2,col,tan,index) { return false; } - draw(context,plist,drawMode,numberOfIndex) {} - destroy(context,plist) {} - - // NOTE: the new buffer data must have the same size as the old one - update(context,plist,bufferType,newData) {} - } - - function createTangents(plist) { - if (!plist.texCoord0 || !plist.vertex) return; - plist._tangent = []; - - let result = []; - let generatedIndexes = {}; - let invalidUV = false; - if (plist.index.length%3==0) { - for (let i=0; i0 && this.normal.length!=this.vertex.length) - throw new Error("Unexpected number of normal coordinates found in polyList"); - - for (let i=0;i { - return a.cameraDistance > b.cameraDistance; - }); - } - - get opaqueQueue() { - return this._opaqueQueue; - } - - get transparentQueue() { - return this._transparentQueue; - } - - - } - - bg.base.RenderQueue = RenderQueue; -})(); -(function() { - - class RenderSurfaceBufferImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) {} - - create(context,attachments) {} - setActive(context,renderSurface) {} - readBuffer(context,renderSurface,rectangle) {} - resize(context,renderSurface,size) {} - destroy(context,renderSurface) {} - supportType(type) {} - supportFormat(format) {} - maxColorAttachments() {} - } - - bg.base.RenderSurfaceBufferImpl = RenderSurfaceBufferImpl; - - class RenderSurface extends bg.app.ContextObject { - static DefaultAttachments() { - return [ - { type:bg.base.RenderSurfaceType.RGBA, format:bg.base.RenderSurfaceFormat.UNSIGNED_BYTE }, - { type:bg.base.RenderSurfaceType.DEPTH, format:bg.base.RenderSurfaceFormat.RENDERBUFFER } - ]; - } - static SupportFormat(format) { - return bg.Engine.Get().colorBuffer.supportFormat(format); - } - - static SupportType(type) { - return bg.Engine.Get().colorBuffer.supportType(type); - } - - static MaxColorAttachments() { - return bg.Engine.Get().textureBuffer.maxColorAttachments; - } - - constructor(context) { - super(context); - - this._size = new bg.Vector2(256); - this._renderSurface = null; - this._resizeOnViewportChanged = true; - } - - get size() { return this._size; } - set size(s) { - if (this._size.x!=s.x || this._size.y!=s.y) { - this._size = s; - this.surfaceImpl.resize(this.context,this._renderSurface,s); - } - } - - get surfaceImpl() { return null; } - - get resizeOnViewportChanged() { return this._resizeOnViewportChanged; } - set resizeOnViewportChanged(r) { this._resizeOnViewportChanged = r; } - - create(attachments) { - if (!attachments) { - attachments = RenderSurface.DefaultAttachments(); - } - this._renderSurface = this.surfaceImpl.create(this.context,attachments); - } - - setActive() { - this.surfaceImpl.setActive(this.context,this._renderSurface); - } - - readBuffer(rectangle) { - return this.surfaceImpl.readBuffer(this.context,this._renderSurface,rectangle,this.size); - } - - destroy() { - this.surfaceImpl.destroy(this.context,this._renderSurface); - this._renderSurface = null; - } - } - - bg.base.RenderSurface = RenderSurface; - - bg.base.RenderSurfaceType = { - RGBA:null, - DEPTH:null - }; - - bg.base.RenderSurfaceFormat = { - UNSIGNED_BYTE:null, - UNSIGNED_SHORT:null, - FLOAT:null, - RENDERBUFFER:null - }; - - class ColorSurface extends RenderSurface { - static MaxColorAttachments() { - return bg.Engine.Get().colorBuffer.maxColorAttachments; - } - - get surfaceImpl() { return bg.Engine.Get().colorBuffer; } - } - - bg.base.ColorSurface = ColorSurface; - - class TextureSurface extends RenderSurface { - static MaxColorAttachments() { - return bg.Engine.Get().textureBuffer.maxColorAttachments; - } - - get surfaceImpl() { return bg.Engine.Get().textureBuffer; } - - getTexture(attachment = 0) { - return this._renderSurface.attachments[attachment] && - this._renderSurface.attachments[attachment].texture; - } - } - - bg.base.TextureSurface = TextureSurface; - -})(); - -(function() { - if (!bg.isElectronApp) { - return false; - } - - const fs = require('fs'); - const path = require('path'); - - class SaveSceneHelper { - save(filePath,sceneRoot) { - filePath = bg.base.Writer.StandarizePath(filePath); - return new Promise((resolve,reject) => { - this._url = {}; - this._url.path = filePath.split('/'); - this._url.fileName = this._url.path.pop(); - this._url.path = this._url.path.join('/'); - this._sceneData = { - fileType:"vwgl::scene", - version:{ - major:2, - minor:0, - rev:0 - }, - scene:[] - } - this._promises = []; - bg.base.Writer.PrepareDirectory(this._url.path); - - let rootNode = {}; - this._sceneData.scene.push(rootNode); - this.buildSceneNode(sceneRoot,rootNode); - - fs.writeFileSync(path.join(this._url.path,this._url.fileName),JSON.stringify(this._sceneData,"","\t"),"utf-8"); - - Promise.all(this._promises) - .then(() => resolve()) - .catch((err) => reject(err)); - }); - } - - buildSceneNode(node,sceneData) { - sceneData.type = "Node"; - sceneData.name = node.name; - sceneData.enabled = node.enabled; - sceneData.steady = node.steady; - sceneData.children = []; - sceneData.components = []; - node.forEachComponent((component) => { - if (component.shouldSerialize) { - let componentData = {}; - component.serialize(componentData,this._promises,this._url); - sceneData.components.push(componentData) - } - }); - node.children.forEach((child) => { - let childData = {} - this.buildSceneNode(child,childData); - sceneData.children.push(childData); - }) - } - }; - - class SceneWriterPlugin extends bg.base.WriterPlugin { - acceptType(url,data) { - let ext = url.split(".").pop("."); - return /vitscnj/i.test(ext) && data instanceof bg.scene.Node; - } - - write(url,data) { - let saveSceneHelper = new SaveSceneHelper(); - return saveSceneHelper.save(url,data); - } - } - - bg.base.SceneWriterPlugin = SceneWriterPlugin; -})(); -(function() { - - let s_shaderLibrary = null; - - function defineAll(obj) { - Reflect.defineProperty(obj,"all", { - get() { - if (!this._all) { - this._all = []; - for (let key in obj) { - if (typeof(obj[key])=="object" && obj[key].name) { - this._all.push(obj[key]); - } - } - } - return this._all; - } - }); - } - - class ShaderLibrary { - static Get() { - if (!s_shaderLibrary) { - s_shaderLibrary = new ShaderLibrary(); - } - return s_shaderLibrary; - } - - constructor() { - let library = bg[bg.Engine.Get().id].shaderLibrary; - - for (let key in library) { - this[key] = library[key]; - } - - defineAll(this.inputs.matrix); - Object.defineProperty(this.inputs.matrix,"modelViewProjection",{ - get() { - return [ - this.model, - this.view, - this.projection - ] - } - }); - defineAll(this.inputs.material); - defineAll(this.inputs.lighting); - defineAll(this.inputs.lightingForward); - defineAll(this.inputs.shadows); - defineAll(this.inputs.colorCorrection); - defineAll(this.functions.materials); - defineAll(this.functions.colorCorrection); - defineAll(this.functions.lighting); - defineAll(this.functions.utils); - } - } - - bg.base.ShaderLibrary = ShaderLibrary; - - class ShaderSourceImpl { - header(shaderType) { return ""; } - parameter(shaderType,paramData) { return paramData.name; } - func(shaderType,funcData) { return funcData.name; } - } - - bg.base.ShaderSourceImpl = ShaderSourceImpl; - - class ShaderSource { - static FormatSource(src) { - let result = ""; - let lines = src.replace(/^\n*/,"").replace(/\n*$/,"").split("\n"); - let minTabs = 100; - lines.forEach((line) => { - let tabsInLine = /(\t*)/.exec(line)[0].length; - if (minTabs>tabsInLine) { - minTabs = tabsInLine; - } - }); - - lines.forEach((line) => { - let tabsInLine = /(\t*)/.exec(line)[0].length; - let diff = tabsInLine - minTabs; - result += line.slice(tabsInLine - diff,line.length) + "\n"; - }); - - return result.replace(/^\n*/,"").replace(/\n*$/,""); - } - - constructor(type) { - this._type = type; - this._params = []; - this._functions = []; - this._requiredExtensions = []; - this._header = ""; - } - - get type() { return this._type; } - get params() { return this._params; } - get header() { return this._header; } - get functions() { return this._functions; } - - addParameter(param) { - if (param instanceof Array) { - this._params = [...this._params, ...param]; - } - else { - this._params.push(param); - } - this._params.push(null); // This will be translated into a new line character - } - - addFunction(func) { - if (func instanceof Array) { - this._functions = [...this._functions, ...func]; - } - else { - this._functions.push(func); - } - } - - setMainBody(body) { - this.addFunction({ - returnType:"void", name:"main", params:{}, body:body - }); - } - - appendHeader(src) { - this._header += src + "\n"; - } - - toString() { - let impl = bg.Engine.Get().shaderSource; - // Build header - let src = impl.header(this.type) + "\n" + this._header + "\n\n"; - - this.params.forEach((p) => { - src += impl.parameter(this.type,p) + "\n"; - }); - - this.functions.forEach((f) => { - src += "\n" + impl.func(this.type,f) + "\n"; - }) - return src; - } - } - - bg.base.ShaderSource = ShaderSource; -})(); -(function() { - - class ShaderImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) {} - setActive(context,shaderProgram) {} - create(context) {} - addShaderSource(context,shaderProgram,shaderType,source) {} - link(context,shaderProgram) {} - initVars(context,shader,inputBufferVars,valueVars) {} - setInputBuffer(context,shader,varName,vertexBuffer,itemSize) {} - setValueInt(context,shader,name,v) {} - setValueIntPtr(context,shader,name,v) {} - setValueFloat(context,shader,name,v) {} - setValueFloatPtr(context,shader,name,v) {} - setValueVector2(context,shader,name,v) {} - setValueVector3(context,shader,name,v) {} - setValueVector4(context,shader,name,v) {} - setValueVector2v(context,shader,name,v) {} - setValueVector3v(context,shader,name,v) {} - setValueVector4v(context,shader,name,v) {} - setValueMatrix3(context,shader,name,traspose,v) {} - setValueMatrix4(context,shader,name,traspose,v) {} - setTexture(context,shader,name,texture,textureUnit) {} - } - - bg.base.ShaderImpl = ShaderImpl; - - bg.base.ShaderType = { - VERTEX: null, - FRAGMENT: null - }; - - function addLineNumbers(source) { - let result = ""; - source.split("\n").forEach((line,index) => { - ++index; - let prefix = index<10 ? "00":index<100 ? "0":""; - result += prefix + index + " | " + line + "\n"; - }); - return result; - } - - class Shader extends bg.app.ContextObject { - static ClearActive(context) { bg.Engine.Get().shader.setActive(context,null); } - - constructor(context) { - super(context); - - this._shader = bg.Engine.Get().shader.create(context); - this._linked = false; - - this._compileError = null; - this._linkError = null; - } - - get shader() { return this._shader; } - get compileError() { return this._compileError; } - get compileErrorSource() { return this._compileErrorSource; } - get linkError() { return this._linkError; } - get status() { return this._compileError==null && this._linkError==null; } - - addShaderSource(shaderType, shaderSource) { - if (this._linked) { - this._compileError = "Tying to attach a shader to a linked program"; - } - else if (!this._compileError) { - this._compileError = bg.Engine.Get().shader.addShaderSource( - this.context, - this._shader, - shaderType,shaderSource); - if (this._compileError) { - this._compileErrorSource = addLineNumbers(shaderSource); - } - } - return this._compileError==null; - } - - link() { - this._linkError = null; - if (this._linked) { - this._linkError = "Shader already linked"; - } - else { - this._linkError = bg.Engine.Get().shader.link(this.context,this._shader); - this._linked = this._linkError==null; - } - return this._linked; - } - - setActive() { - bg.Engine.Get().shader.setActive(this.context,this._shader); - } - - clearActive() { - Shader.ClearActive(this.context); - } - - initVars(inputBufferVars,valueVars) { - bg.Engine.Get().shader.initVars(this.context,this._shader,inputBufferVars,valueVars); - } - - setInputBuffer(name,vbo,itemSize) { - bg.Engine.Get().shader - .setInputBuffer(this.context,this._shader,name,vbo,itemSize); - } - - disableInputBuffer(name) { - bg.Engine.Get().shader - .disableInputBuffer(this.context,this._shader,name); - } - - setValueInt(name,v) { - bg.Engine.Get().shader - .setValueInt(this.context,this._shader,name,v); - } - - setValueIntPtr(name,v) { - bg.Engine.Get().shader - .setValueIntPtr(this.context,this._shader,name,v); - } - - setValueFloat(name,v) { - bg.Engine.Get().shader - .setValueFloat(this.context,this._shader,name,v); - } - - setValueFloatPtr(name,v) { - bg.Engine.Get().shader - .setValueFloatPtr(this.context,this._shader,name,v); - } - - setVector2(name,v) { - bg.Engine.Get().shader - .setValueVector2(this.context,this._shader,name,v); - } - - setVector3(name,v) { - bg.Engine.Get().shader - .setValueVector3(this.context,this._shader,name,v); - } - - setVector4(name,v) { - bg.Engine.Get().shader - .setValueVector4(this.context,this._shader,name,v); - } - - setVector2Ptr(name,v) { - bg.Engine.Get().shader - .setValueVector2v(this.context,this._shader,name,v); - } - - setVector3Ptr(name,v) { - bg.Engine.Get().shader - .setValueVector3v(this.context,this._shader,name,v); - } - - setVector4Ptr(name,v) { - bg.Engine.Get().shader - .setValueVector4v(this.context,this._shader,name,v); - } - - setMatrix3(name,v,traspose=false) { - bg.Engine.Get().shader - .setValueMatrix3(this.context,this._shader,name,traspose,v); - } - - setMatrix4(name,v,traspose=false) { - bg.Engine.Get().shader - .setValueMatrix4(this.context,this._shader,name,traspose,v); - } - - setTexture(name,texture,textureUnit) { - bg.Engine.Get().shader - .setTexture(this.context,this._shader,name,texture,textureUnit); - } - } - - bg.base.Shader = Shader; -})(); -(function() { - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - let s_vertexSource = null; - let s_fragmentSource = null; - - function vertexShaderSource() { - if (!s_vertexSource) { - s_vertexSource = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_vertexSource.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - null, - lib().inputs.matrix.model, - lib().inputs.matrix.view, - lib().inputs.matrix.projection, - null, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_vertexSource.setMainBody(` - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - fsTexCoord = inTex0; - `); - } - } - return s_vertexSource; - } - - function fragmentShaderSource() { - if (!s_fragmentSource) { - s_fragmentSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - s_fragmentSource.addParameter([ - lib().inputs.material.castShadows, - lib().inputs.material.texture, - lib().inputs.material.textureOffset, - lib().inputs.material.textureScale, - lib().inputs.material.alphaCutoff, - null, - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ]); - - s_fragmentSource.addFunction(lib().functions.utils.pack); - s_fragmentSource.addFunction(lib().functions.materials.samplerColor); - - if (bg.Engine.Get().id=="webgl1") { - s_fragmentSource.setMainBody(` - - float alpha = samplerColor(inTexture,fsTexCoord,inTextureOffset,inTextureScale).a; - if (inCastShadows && alpha>inAlphaCutoff) { - gl_FragColor = pack(gl_FragCoord.z); - } - else { - discard; - }`); - } - } - return s_fragmentSource; - } - - class ShadowMapEffect extends bg.base.Effect { - constructor(context) { - super(context); - - this._material = null; - this._light = null; - this._lightTransform = null; - - this.setupShaderSource([ - vertexShaderSource(), - fragmentShaderSource() - ]); - } - - get material() { return this._material; } - set material(m) { this._material = m; } - - get light() { return this._light; } - set light(l) { this._light = l; } - - get lightTransform() { return this._lightTransform; } - set lightTransform(t) { this._lightTransform = t; } - - setupVars() { - if (this.material && this.light && this.lightTransform) { - let matrixState = bg.base.MatrixState.Current(); - this.shader.setMatrix4("inModelMatrix",matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4("inViewMatrix",this.lightTransform); - this.shader.setMatrix4("inProjectionMatrix",this.light.projection); - - this.shader.setValueInt("inCastShadows",this.material.castShadows); - let texture = this.material.texture || bg.base.TextureCache.WhiteTexture(this.context); - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2("inTextureOffset",this.material.textureOffset); - this.shader.setVector2("inTextureScale",this.material.textureScale); - this.shader.setValueFloat("inAlphaCutoff",this.material.alphaCutoff); - } - } - } - - bg.base.ShadowMapEffect = ShadowMapEffect; - - bg.base.ShadowType = { - HARD: 0, - SOFT: 1, - STRATIFIED: 2 - }; - - bg.base.ShadowCascade = { - NEAR: 0, - FAR: 1, - MID: 2 - } - - function updateDirectional(scene,camera,light,lightTransform,cascade) { - let ms = bg.base.MatrixState.Current(); - bg.base.MatrixState.SetCurrent(this._matrixState); - this._pipeline.effect.light = light; - this._viewMatrix = new bg.Matrix4(lightTransform); - - let rotation = this._viewMatrix.rotation; - let cameraTransform = camera.transform ? new bg.Matrix4(camera.transform.matrix) : bg.Matrix4.Identity(); - let cameraPos = cameraTransform.position; - let target = cameraPos.add(cameraTransform.forwardVector.scale(-camera.focus)) - - this._viewMatrix - .identity() - .translate(target) - .mult(rotation) - .translate(0,0,10) - .invert(); - - this._pipeline.effect.lightTransform = this._viewMatrix; - - bg.base.Pipeline.SetCurrent(this._pipeline); - this._pipeline.clearBuffers(bg.base.ClearBuffers.COLOR_DEPTH); - - let mult = 1; - // Far cascade - if (cascade==bg.base.ShadowCascade.FAR) { - mult = 20; - light.shadowBias = 0.0001; - } - // Near cascade - else if (cascade==bg.base.ShadowCascade.NEAR) { - mult = 2; - light.shadowBias = 0.00002; - } - else if (cascade==bg.base.ShadowCascade.MID) { - mult = 4; - light.shadowBias = 0.0001; - } - light.projection = bg.Matrix4.Ortho(-camera.focus * mult ,camera.focus * mult,-camera.focus * mult,camera.focus * mult,1,300*camera.focus); - this._projection = light.projection; - scene.accept(this._drawVisitor); - - bg.base.MatrixState.SetCurrent(ms); - } - - function updateSpot(scene,camera,light,lightTransform) { - let ms = bg.base.MatrixState.Current(); - bg.base.MatrixState.SetCurrent(this._matrixState); - this._pipeline.effect.light = light; - this._viewMatrix = new bg.Matrix4(lightTransform); - - let cutoff = light.spotCutoff; - light.projection = bg.Matrix4.Perspective(cutoff * 2,1,0.1,200.0); - light.shadowBias = 0.0005; - this._viewMatrix.invert(); - - this._projection = light.projection; - this._pipeline.effect.lightTransform = this._viewMatrix; - - bg.base.Pipeline.SetCurrent(this._pipeline); - this._pipeline.clearBuffers(bg.base.ClearBuffers.COLOR_DEPTH); - - scene.accept(this._drawVisitor); - bg.base.MatrixState.SetCurrent(ms); - } - - class ShadowMap extends bg.app.ContextObject { - constructor(context) { - super(context); - - this._pipeline = new bg.base.Pipeline(context); - this._pipeline.renderSurface = new bg.base.TextureSurface(context); - this._pipeline.renderSurface.create(); - this._pipeline.effect = new bg.base.ShadowMapEffect(context); - - this._matrixState = new bg.base.MatrixState(); - this._drawVisitor = new bg.scene.DrawVisitor(this._pipeline,this._matrixState); - - this._shadowMapSize = new bg.Vector2(2048); - this._pipeline.viewport = new bg.Viewport(0,0,this._shadowMapSize.width,this._shadowMapSize.height); - - this._shadowType = bg.base.ShadowType.SOFT; - - this._projection = bg.Matrix4.Ortho(-15,15,-15,15,1,50); - this._viewMatrix = bg.Matrix4.Identity(); - - this._shadowColor = bg.Color.Black(); - } - - get size() { return this._shadowMapSize; } - set size(s) { - this._shadowMapSize = s; - this._pipeline.viewport = new bg.Viewport(0,0,s.width,s.height); - } - - get shadowType() { return this._shadowType; } - set shadowType(t) { this._shadowType = t; } - - get shadowColor() { return this._shadowColor; } - set shadowColor(c) { this._shadowColor = c; } - - get viewMatrix() { return this._viewMatrix; } - get projection() { return this._projection; } - - get texture() { return this._pipeline.renderSurface.getTexture(0); } - - // it's important that the camera has set the focus to calculate the projection of the directional lights - update(scene,camera,light,lightTransform,cascade=bg.base.ShadowCascade.NEAR) { - if (light.type==bg.base.LightType.DIRECTIONAL) { - updateDirectional.apply(this,[scene,camera,light,lightTransform,cascade]); - } - else if (light.type==bg.base.LightType.SPOT) { - updateSpot.apply(this,[scene,camera,light,lightTransform]); - } - } - } - - bg.base.ShadowMap = ShadowMap; - -})(); -(function() { - - class TextProperties { - - constructor() { - this._font = "Verdana"; - this._size = 30; - this._color = "#FFFFFF"; - this._background = "transparent"; - this._align = "start"; - this._bold = false; - this._italic = false; - - this._dirty = true; - } - - clone() { - let newInstance = new TextProperties(); - - newInstance._font = this._font; - newInstance._size = this._size; - newInstance._color = this._color; - newInstance._background = this._background; - newInstance._align = this._align; - newInstance._bold = this._bold; - newInstance._italic = this._italic; - - return newInstance; - } - - get font() { return this._font; } - set font(v) { this._dirty = true; this._font = v; } - get size() { return this._size; } - set size(v) { this._dirty = true; this._size = v; } - get color() { return this._color; } - set color(v) { this._dirty = true; this._color = v; } - get background() { return this._background; } - set background(v) { this._dirty = true; this._background = v; } - get align() { return this._align; } - set align(v) { this._dirty = true; this._align = v; } - get bold() { return this._bold; } - set bold(v) { this._dirty = true; this._bold = v; } - get italic() { return this._italic; } - set italic(v) { this._dirty = true; this._italic = v; } - - - // this property is set to true every time some property is changed - set dirty(d) { this._dirty = d; } - get dirty() { return this._dirty; } - - serialize(jsonData) { - jsonData.font = this.font; - jsonData.size = this.size; - jsonData.color = this.color; - jsonData.background = this.background; - jsonData.align = this.align; - jsonData.bold = this.bold; - jsonData.italic = this.italic; - } - - deserialize(jsonData) { - this.font = jsonData.font; - this.size = jsonData.size; - this.color = jsonData.color; - this.background = jsonData.background; - this.align = jsonData.align; - this.bold = jsonData.bold; - this.italic = jsonData.italic; - this._dirty = true; - } - } - - bg.base.TextProperties = TextProperties; -})(); -(function() { - let s_textureCache = {}; - - let COLOR_TEXTURE_SIZE = 8; - - let s_whiteTexture = "static-white-color-texture"; - let s_blackTexture = "static-black-color-texture"; - let s_normalTexture = "static-normal-color-texture"; - let s_randomTexture = "static-random-color-texture"; - let s_whiteCubemap = "static-white-cubemap-texture"; - - class TextureCache { - static SetColorTextureSize(size) { COLOR_TEXTURE_SIZE = size; } - static GetColorTextureSize() { return COLOR_TEXTURE_SIZE; } - - static WhiteCubemap(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_whiteCubemap); - - if (!tex) { - tex = bg.base.Texture.WhiteCubemap(context); - cache.register(s_whiteCubemap,tex); - } - return tex; - } - - static WhiteTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_whiteTexture); - - if (!tex) { - tex = bg.base.Texture.WhiteTexture(context,new bg.Vector2(COLOR_TEXTURE_SIZE)); - cache.register(s_whiteTexture,tex); - } - - return tex; - } - - static BlackTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_blackTexture); - - if (!tex) { - tex = bg.base.Texture.BlackTexture(context,new bg.Vector2(COLOR_TEXTURE_SIZE)); - cache.register(s_blackTexture,tex); - } - - return tex; - } - - static NormalTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_normalTexture); - - if (!tex) { - tex = bg.base.Texture.NormalTexture(context,new bg.Vector2(COLOR_TEXTURE_SIZE)); - cache.register(s_normalTexture,tex); - } - - return tex; - } - - static RandomTexture(context) { - let cache = TextureCache.Get(context); - let tex = cache.find(s_randomTexture); - - if (!tex) { - tex = bg.base.Texture.RandomTexture(context,new bg.Vector2(64)); - cache.register(s_randomTexture,tex); - } - - return tex; - } - - static Get(context) { - if (!s_textureCache[context.uuid]) { - s_textureCache[context.uuid] = new TextureCache(context); - } - return s_textureCache[context.uuid]; - } - - constructor(context) { - this._context = context; - this._textures = {}; - } - - find(url) { - return this._textures[url]; - } - - register(url,texture) { - if (texture instanceof bg.base.Texture) { - this._textures[url] = texture; - } - } - - unregister(url) { - if (this._textures[url]) { - delete this._textures[url]; - } - } - - clear() { - this._textures = {}; - } - } - - bg.base.TextureCache = TextureCache; - - let g_wrapX = null; - let g_wrapY = null; - let g_minFilter = null; - let g_magFilter = null; - - /* Extra data: - * wrapX - * wrapY - * minFilter - * magFilter - */ - class TextureLoaderPlugin extends bg.base.LoaderPlugin { - static GetWrapX() { - return g_wrapX || bg.base.TextureWrap.REPEAT; - } - - static GetWrapY() { - return g_wrapY || bg.base.TextureWrap.REPEAT; - } - - static GetMinFilter() { - return g_minFilter || bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST; - } - - static GetMagFilter() { - return g_magFilter || bg.base.TextureFilter.LINEAR; - } - - static SetMinFilter(f) { - g_minFilter = f; - } - - static SetMagFilter(f) { - g_magFilter = f; - } - - static SetWrapX(w) { - g_wrapX = w; - } - - static SetWrapY(w) { - g_wrapY = w; - } - - acceptType(url,data) { - return bg.utils.Resource.IsImage(url); - } - - load(context,url,data,extraData) { - return new Promise((accept,reject) => { - if (data) { - let texture = bg.base.TextureCache.Get(context).find(url); - if (!texture) { - bg.log(`Texture ${url} not found. Loading texture`); - texture = new bg.base.Texture(context); - texture.create(); - texture.bind(); - texture.wrapX = extraData.wrapX || TextureLoaderPlugin.GetWrapX(); - texture.wrapY = extraData.wrapY || TextureLoaderPlugin.GetWrapY(); - texture.minFilter = extraData.minFilter || TextureLoaderPlugin.GetMinFilter(); - texture.magFilter = extraData.magFilter || TextureLoaderPlugin.GetMagFilter(); - texture.setImage(data); - texture.fileName = url; - bg.base.TextureCache.Get(context).register(url,texture); - } - accept(texture); - } - else { - reject(new Error("Error loading texture image data")); - } - }); - } - } - - bg.base.TextureLoaderPlugin = TextureLoaderPlugin; - - class VideoTextureLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - return bg.utils.Resource.IsVideo(url); - } - - load(context,url,video) { - return new Promise((accept,reject) => { - if (video) { - let texture = new bg.base.Texture(context); - texture.create(); - texture.bind(); - texture.setVideo(video); - texture.fileName = url; - accept(texture); - } - else { - reject(new Error("Error loading video texture data")); - } - }); - } - } - - bg.base.VideoTextureLoaderPlugin = VideoTextureLoaderPlugin; -})(); -(function() { - - bg.base.TextureUnit = { - TEXTURE_0: 0, - TEXTURE_1: 1, - TEXTURE_2: 2, - TEXTURE_3: 3, - TEXTURE_4: 4, - TEXTURE_5: 5, - TEXTURE_6: 6, - TEXTURE_7: 7, - TEXTURE_8: 8, - TEXTURE_9: 9, - TEXTURE_10: 10, - TEXTURE_11: 11, - TEXTURE_12: 12, - TEXTURE_13: 13, - TEXTURE_14: 14, - TEXTURE_15: 15, - TEXTURE_16: 16, - TEXTURE_17: 17, - TEXTURE_18: 18, - TEXTURE_19: 19, - TEXTURE_20: 20, - TEXTURE_21: 21, - TEXTURE_22: 22, - TEXTURE_23: 23, - TEXTURE_24: 24, - TEXTURE_25: 25, - TEXTURE_26: 26, - TEXTURE_27: 27, - TEXTURE_28: 28, - TEXTURE_29: 29, - TEXTURE_30: 30 - }; - - bg.base.TextureWrap = { - REPEAT: null, - CLAMP: null, - MIRRORED_REPEAT: null - }; - - bg.base.TextureFilter = { - NEAREST_MIPMAP_NEAREST: null, - LINEAR_MIPMAP_NEAREST: null, - NEAREST_MIPMAP_LINEAR: null, - LINEAR_MIPMAP_LINEAR: null, - NEAREST: null, - LINEAR: null - }; - - bg.base.TextureTarget = { - TEXTURE_2D: null, - CUBE_MAP: null, - POSITIVE_X_FACE: null, - NEGATIVE_X_FACE: null, - POSITIVE_Y_FACE: null, - NEGATIVE_Y_FACE: null, - POSITIVE_Z_FACE: null, - NEGATIVE_Z_FACE: null - }; - - class TextureImpl { - constructor(context) { - this.initFlags(context); - } - - initFlags(context) { - console.log("TextureImpl: initFlags() method not implemented"); - } - - create(context) { - console.log("TextureImpl: create() method not implemented"); - return null; - } - - setActive(context,texUnit) { - console.log("TextureImpl: setActive() method not implemented"); - } - - bind(context,target,texture) { - console.log("TextureImpl: bind() method not implemented"); - } - - unbind(context,target) { - console.log("TextureImpl: unbind() method not implemented"); - } - - setTextureWrapX(context,target,texture,wrap) { - console.log("TextureImpl: setTextureWrapX() method not implemented"); - } - - setTextureWrapY(context,target,texture,wrap) { - console.log("TextureImpl: setTextureWrapY() method not implemented"); - } - - setImage(context,target,minFilter,magFilter,texture,img,flipY) { - console.log("TextureImpl: setImage() method not implemented"); - } - - setImageRaw(context,target,minFilter,magFilter,texture,width,height,data) { - console.log("TextureImpl: setImageRaw() method not implemented"); - } - - setTextureFilter(context,target,minFilter,magFilter) { - console.log("TextureImpl: setTextureFilter() method not implemented"); - } - - setCubemapImage(context,face,image) { - console.log("TextureImpl: setCubemapImage() method not implemented"); - } - - setCubemapRaw(context,face,rawImage,w,h) { - console.log("TextureImpl: setCubemapRaw() method not implemented"); - } - - setVideo(context,target,texture,video,flipY) { - console.log("TextureImpl: setVideo() method not implemented"); - } - - updateVideoData(context,target,texture,video) { - console.log("TextureImpl: updateVideoData() method not implemented"); - } - - destroy(context,texture) { - console.log("TextureImpl: destroy() method not implemented"); - } - } - - bg.base.TextureImpl = TextureImpl; - - bg.base.TextureDataType = { - NONE: 0, - IMAGE: 1, - IMAGE_DATA: 2, - CUBEMAP: 3, - CUBEMAP_DATA: 4, - VIDEO: 5 - }; - - let g_base64TexturePreventRemove = []; - - class Texture extends bg.app.ContextObject { - static IsPowerOfTwoImage(image) { - return bg.Math.checkPowerOfTwo(image.width) && bg.Math.checkPowerOfTwo(image.height); - } - - static FromCanvas(context,canvas2d) { - return Texture.FromBase64Image(context,canvas2d.toDataURL("image/png")); - } - - static UpdateCanvasImage(texture,canvas2d) { - if (!texture.valid) { - return false; - } - let imageData = canvas2d.toDataURL("image/png"); - let recreate = false; - if (texture.img.width!=imageData.width || texture.img.height!=imageData.height) { - recreate = true; - } - texture.img = new Image(); - g_base64TexturePreventRemove.push(texture); - //tex.onload = function(evt,img) { - // Check this: use onload or setTimeout? - // onload seems to not work in all situations - setTimeout(() => { - texture.bind(); - if (Texture.IsPowerOfTwoImage(texture.img)) { - texture.minFilter = bg.base.TextureLoaderPlugin.GetMinFilter(); - texture.magFilter = bg.base.TextureLoaderPlugin.GetMagFilter(); - } - else { - texture.minFilter = bg.base.TextureFilter.NEAREST; - texture.magFilter = bg.base.TextureFilter.NEAREST; - texture.wrapX = bg.base.TextureWrap.CLAMP; - texture.wrapY = bg.base.TextureWrap.CLAMP; - } - texture.setImage(texture.img,true); - texture.unbind(); - let index = g_base64TexturePreventRemove.indexOf(texture); - if (index!=-1) { - g_base64TexturePreventRemove.splice(index,1); - } - bg.emitImageLoadEvent(); - //} - },10); - texture.img.src = imageData; - - return texture; - } - - static FromBase64Image(context,imgData) { - let tex = new bg.base.Texture(context); - tex.img = new Image(); - g_base64TexturePreventRemove.push(tex); - //tex.onload = function(evt,img) { - // Check this: use onload or setTimeout? - // onload seems to not work in all situations - setTimeout(() => { - tex.create(); - tex.bind(); - if (Texture.IsPowerOfTwoImage(tex.img)) { - tex.minFilter = bg.base.TextureLoaderPlugin.GetMinFilter(); - tex.magFilter = bg.base.TextureLoaderPlugin.GetMagFilter(); - } - else { - tex.minFilter = bg.base.TextureFilter.NEAREST; - tex.magFilter = bg.base.TextureFilter.NEAREST; - tex.wrapX = bg.base.TextureWrap.CLAMP; - tex.wrapY = bg.base.TextureWrap.CLAMP; - } - tex.setImage(tex.img,false); // Check this: flip base64 image? - tex.unbind(); - let index = g_base64TexturePreventRemove.indexOf(tex); - if (index!=-1) { - g_base64TexturePreventRemove.splice(index,1); - } - bg.emitImageLoadEvent(); - //} - },10); - tex.img.src = imgData; - - return tex; - } - - static ColorTexture(context,color,size) { - let colorTexture = new bg.base.Texture(context); - colorTexture.create(); - colorTexture.bind(); - - var dataSize = size.width * size.height * 4; - var textureData = []; - for (var i = 0; i < dataSize; i+=4) { - textureData[i] = color.r * 255; - textureData[i+1] = color.g * 255; - textureData[i+2] = color.b * 255; - textureData[i+3] = color.a * 255; - } - - textureData = new Uint8Array(textureData); - - colorTexture.minFilter = bg.base.TextureFilter.NEAREST; - colorTexture.magFilter = bg.base.TextureFilter.NEAREST; - colorTexture.setImageRaw(size.width,size.height,textureData); - colorTexture.unbind(); - - return colorTexture; - } - - static WhiteTexture(context,size) { - return Texture.ColorTexture(context,bg.Color.White(),size); - } - - static WhiteCubemap(context) { - return Texture.ColorCubemap(context, bg.Color.White()); - } - - static BlackCubemap(context) { - return Texture.ColorCubemap(context, bg.Color.Black()); - } - - static ColorCubemap(context,color) { - let cm = new bg.base.Texture(context); - cm.target = bg.base.TextureTarget.CUBE_MAP; - cm.create(); - cm.bind(); - - let dataSize = 32 * 32 * 4; - let textureData = []; - for (let i = 0; i-this.EPSILON && v=2) { - vec = vec._v; - } - let x=vec[0]; - let y=vec[1]; - let z=1.0; - - return new bg.Vector3( this._m[0]*x + this._m[3]*y + this._m[6]*z, - this._m[1]*x + this._m[4]*y + this._m[7]*z, - this._m[2]*x + this._m[5]*y + this._m[8]*z); - } - - isNan() { - return !Math.isNaN(_m[0]) && !Math.isNaN(_m[1]) && !Math.isNaN(_m[2]) && - !Math.isNaN(_m[3]) && !Math.isNaN(_m[4]) && !Math.isNaN(_m[5]) && - !Math.isNaN(_m[6]) && !Math.isNaN(_m[7]) && !Math.isNaN(_m[8]); - } - - toString() { - return "[" + this._m[0] + ", " + this._m[1] + ", " + this._m[2] + "]\n" + - " [" + this._m[3] + ", " + this._m[4] + ", " + this._m[5] + "]\n" + - " [" + this._m[6] + ", " + this._m[7] + ", " + this._m[8] + "]"; - } -} - -bg.Matrix3 = Matrix3; - -class Matrix4 { - static Unproject(x, y, depth, mvMat, pMat, viewport) { - let mvp = new bg.Matrix4(pMat); - mvp.mult(mvMat); - mvp.invert(); - - let vin = new bg.Vector4(((x - viewport.y) / viewport.width) * 2.0 - 1.0, - ((y - viewport.x) / viewport.height) * 2.0 - 1.0, - depth * 2.0 - 1.0, - 1.0); - - let result = new bg.Vector4(mvp.multVector(vin)); - if (result.z==0) { - result.set(0); - } - else { - result.set( result.x/result.w, - result.y/result.w, - result.z/result.w, - result.w/result.w); - } - - return result; - } - - static Identity() { - return new bg.Matrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); - } - - static Perspective(fovy, aspect, nearPlane, farPlane) { - let fovy2 = bg.Math.tan(fovy * bg.Math.PI / 360.0) * nearPlane; - let fovy2aspect = fovy2 * aspect; - - return bg.Matrix4.Frustum(-fovy2aspect,fovy2aspect,-fovy2,fovy2,nearPlane,farPlane); - } - - static Frustum(left, right, bottom, top, nearPlane, farPlane) { - let res = new bg.Matrix4(); - let A = right-left; - let B = top-bottom; - let C = farPlane-nearPlane; - - res.setRow(0, new bg.Vector4(nearPlane*2.0/A, 0.0, 0.0, 0.0)); - res.setRow(1, new bg.Vector4(0.0, nearPlane*2.0/B, 0.0, 0.0)); - res.setRow(2, new bg.Vector4((right+left)/A, (top+bottom)/B, -(farPlane+nearPlane)/C, -1.0)); - res.setRow(3, new bg.Vector4(0.0, 0.0, -(farPlane*nearPlane*2.0)/C, 0.0)); - - return res; - } - - static Ortho(left, right, bottom, top, nearPlane, farPlane) { - let p = new bg.Matrix4(); - - let m = right-left; - let l = top-bottom; - let k = farPlane-nearPlane;; - - p._m[0] = 2/m; p._m[1] = 0; p._m[2] = 0; p._m[3] = 0; - p._m[4] = 0; p._m[5] = 2/l; p._m[6] = 0; p._m[7] = 0; - p._m[8] = 0; p._m[9] = 0; p._m[10] = -2/k; p._m[11]= 0; - p._m[12]=-(left+right)/m; p._m[13] = -(top+bottom)/l; p._m[14] = -(farPlane+nearPlane)/k; p._m[15]=1; - - return p; - } - - static LookAt(p_eye, p_center, p_up) { - let result = new bg.Matrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); - let forward = new bg.Vector3(p_center); - forward.sub(p_eye); - let up = new bg.Vector3(p_up); - - forward.normalize(); - - let side = new bg.Vector3(forward); - side.cross(up); - up.assign(side); - up.cross(forward); - - result.set00(side.x); result.set10(side.y); result.set20(side.z); - result.set01(up.x); result.set11(up.y); result.set21(up.z); - result.set02(-forward.x); result.set12(-forward.y); result.set22(-forward.z); - result.setRow(3, new vwgl.Vector4(-p_eye.x,-p_eye.y,-p_eye.z,1.0)); - - return result; - } - - static Translation(x, y, z) { - if (typeof(x)=='object' && x._v && x._v.length>=3) { - y = x._v[1]; - z = x._v[2]; - x = x._v[0]; - } - return new bg.Matrix4( - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - x, y, z, 1.0 - ); - } - - static Rotation(alpha, x, y, z) { - let axis = new bg.Vector3(x,y,z); - axis.normalize(); - let rot = new bg.Matrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); - - var cosAlpha = bg.Math.cos(alpha); - var acosAlpha = 1.0 - cosAlpha; - var sinAlpha = bg.Math.sin(alpha); - - return new bg.Matrix4( - axis.x * axis.x * acosAlpha + cosAlpha, axis.x * axis.y * acosAlpha + axis.z * sinAlpha, axis.x * axis.z * acosAlpha - axis.y * sinAlpha, 0, - axis.y * axis.x * acosAlpha - axis.z * sinAlpha, axis.y * axis.y * acosAlpha + cosAlpha, axis.y * axis.z * acosAlpha + axis.x * sinAlpha, 0, - axis.z * axis.x * acosAlpha + axis.y * sinAlpha, axis.z * axis.y * acosAlpha - axis.x * sinAlpha, axis.z * axis.z * acosAlpha + cosAlpha, 0, - 0,0,0,1 - ); - } - - static Scale(x, y, z) { - if (typeof(x)=='object' && x._v && x._v.length>=3) { - x = x._v[0]; - y = x._v[1]; - z = x._v[2]; - } - return new bg.Matrix4( - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 - ) - } - - constructor(m00=0,m01=0,m02=0,m03=0, m10=0,m11=0,m12=0,m13=0, m20=0,m21=0,m22=0,m23=0, m30=0,m31=0,m32=0,m33=0) { - this._m = new bg.Math.Array(16); - if (Array.isArray(m00)) { - this._m[ 0] = m00[0]; this._m[ 1] = m00[1]; this._m[ 2] = m00[2]; this._m[ 3] = m00[3]; - this._m[ 4] = m00[4]; this._m[ 5] = m00[5]; this._m[ 6] = m00[6]; this._m[ 7] = m00[7]; - this._m[ 8] = m00[8]; this._m[ 9] = m00[9]; this._m[10] = m00[10]; this._m[11] = m00[11]; - this._m[12] = m00[12]; this._m[13] = m00[13]; this._m[14] = m00[14]; this._m[15] = m00[15]; - } - else if (typeof(m00)=="number") { - this._m[ 0] = m00; this._m[ 1] = m01; this._m[ 2] = m02; this._m[ 3] = m03; - this._m[ 4] = m10; this._m[ 5] = m11; this._m[ 6] = m12; this._m[ 7] = m13; - this._m[ 8] = m20; this._m[ 9] = m21; this._m[10] = m22; this._m[11] = m23; - this._m[12] = m30; this._m[13] = m31; this._m[14] = m32; this._m[15] = m33; - } - else { - this.assign(m00); - } - } - - get m() { return this._m; } - - toArray() { - return [ - this._m[ 0], this._m[ 1], this._m[ 2], this._m[ 3], - this._m[ 4], this._m[ 5], this._m[ 6], this._m[ 7], - this._m[ 8], this._m[ 9], this._m[10], this._m[11], - this._m[12], this._m[13], this._m[14], this._m[15] - ] - } - - get m00() { return this._m[0]; } - get m01() { return this._m[1]; } - get m02() { return this._m[2]; } - get m03() { return this._m[3]; } - get m10() { return this._m[4]; } - get m11() { return this._m[5]; } - get m12() { return this._m[6]; } - get m13() { return this._m[7]; } - get m20() { return this._m[8]; } - get m21() { return this._m[9]; } - get m22() { return this._m[10]; } - get m23() { return this._m[11]; } - get m30() { return this._m[12]; } - get m31() { return this._m[13]; } - get m32() { return this._m[14]; } - get m33() { return this._m[15]; } - - set m00(v) { this._m[0] = v; } - set m01(v) { this._m[1] = v; } - set m02(v) { this._m[2] = v; } - set m03(v) { this._m[3] = v; } - set m10(v) { this._m[4] = v; } - set m11(v) { this._m[5] = v; } - set m12(v) { this._m[6] = v; } - set m13(v) { this._m[7] = v; } - set m20(v) { this._m[8] = v; } - set m21(v) { this._m[9] = v; } - set m22(v) { this._m[10] = v; } - set m23(v) { this._m[11] = v; } - set m30(v) { this._m[12] = v; } - set m31(v) { this._m[13] = v; } - set m32(v) { this._m[14] = v; } - set m33(v) { this._m[15] = v; } - - - zero() { - this._m[ 0] = 0; this._m[ 1] = 0; this._m[ 2] = 0; this._m[ 3] = 0; - this._m[ 4] = 0; this._m[ 5] = 0; this._m[ 6] = 0; this._m[ 7] = 0; - this._m[ 8] = 0; this._m[ 9] = 0; this._m[10] = 0; this._m[11] = 0; - this._m[12] = 0; this._m[13] = 0; this._m[14] = 0; this._m[15] = 0; - return this; - } - - identity() { - this._m[ 0] = 1; this._m[ 1] = 0; this._m[ 2] = 0; this._m[ 3] = 0; - this._m[ 4] = 0; this._m[ 5] = 1; this._m[ 6] = 0; this._m[ 7] = 0; - this._m[ 8] = 0; this._m[ 9] = 0; this._m[10] = 1; this._m[11] = 0; - this._m[12] = 0; this._m[13] = 0; this._m[14] = 0; this._m[15] = 1; - return this; - } - - isZero() { - return this._m[ 0]==0 && this._m[ 1]==0 && this._m[ 2]==0 && this._m[ 3]==0 && - this._m[ 4]==0 && this._m[ 5]==0 && this._m[ 6]==0 && this._m[ 7]==0 && - this._m[ 8]==0 && this._m[ 9]==0 && this._m[10]==0 && this._m[11]==0 && - this._m[12]==0 && this._m[13]==0 && this._m[14]==0 && this._m[15]==0; - } - - isIdentity() { - return this._m[ 0]==1 && this._m[ 1]==0 && this._m[ 2]==0 && this._m[ 3]==0 && - this._m[ 4]==0 && this._m[ 5]==1 && this._m[ 6]==0 && this._m[ 7]==0 && - this._m[ 8]==0 && this._m[ 9]==0 && this._m[10]==1 && this._m[11]==0 && - this._m[12]==0 && this._m[13]==0 && this._m[14]==0 && this._m[15]==1; - } - - row(i) { return new bg.Vector4(this._m[i*4],this._m[i*4 + 1],this._m[i*4 + 2],this._m[i*4 + 3]); } - setRow(i, row) { this._m[i*4]=row._v[0]; this._m[i*4 + 1]=row._v[1]; this._m[i*4 + 2]=row._v[2]; this._m[i*4 + 3]=row._v[3]; return this; } - setScale(x,y,z) { - let rx = new bg.Vector3(this._m[0], this._m[4], this._m[8]).normalize().scale(x); - let ry = new bg.Vector3(this._m[1], this._m[5], this._m[9]).normalize().scale(y); - let rz = new bg.Vector3(this._m[2], this._m[6], this._m[10]).normalize().scale(z); - this._m[0] = rx.x; this._m[4] = rx.y; this._m[8] = rx.z; - this._m[1] = ry.x; this._m[5] = ry.y; this._m[9] = ry.z; - this._m[2] = rz.x; this._m[6] = rz.y; this._m[10] = rz.z; - return this; - } - getScale() { - return new bg.Vector3( - new bg.Vector3(this._m[0], this._m[4], this._m[8]).module, - new bg.Vector3(this._m[1], this._m[5], this._m[9]).module, - new bg.Vector3(this._m[2], this._m[6], this._m[10]).module - ); - } - - setPosition(pos,y,z) { - if (typeof(pos)=="number") { - this._m[12] = pos; - this._m[13] = y; - this._m[14] = z; - } - else { - this._m[12] = pos.x; - this._m[13] = pos.y; - this._m[14] = pos.z; - } - return this; - } - - get rotation() { - let scale = this.getScale(); - return new bg.Matrix4( - this._m[0]/scale.x, this._m[1]/scale.y, this._m[ 2]/scale.z, 0, - this._m[4]/scale.x, this._m[5]/scale.y, this._m[ 6]/scale.z, 0, - this._m[8]/scale.x, this._m[9]/scale.y, this._m[10]/scale.z, 0, - 0, 0, 0, 1 - ); - } - - get position() { - return new bg.Vector3(this._m[12], this._m[13], this._m[14]); - } - - get length() { return this._m.length; } - - getMatrix3() { - return new bg.Matrix3(this._m[0], this._m[1], this._m[ 2], - this._m[4], this._m[5], this._m[ 6], - this._m[8], this._m[9], this._m[10]); - } - - perspective(fovy, aspect, nearPlane, farPlane) { - this.assign(bg.Matrix4.Perspective(fovy, aspect, nearPlane, farPlane)); - return this; - } - - frustum(left, right, bottom, top, nearPlane, farPlane) { - this.assign(bg.Matrix4.Frustum(left, right, bottom, top, nearPlane, farPlane)); - return this; - } - - ortho(left, right, bottom, top, nearPlane, farPlane) { - this.assign(bg.Matrix4.Ortho(left, right, bottom, top, nearPlane, farPlane)); - return this; - } - - lookAt(origin, target, up) { - this.assign(bg.Matrix4.LookAt(origin,target,up)); - return this; - } - - translate(x, y, z) { - this.mult(bg.Matrix4.Translation(x, y, z)); - return this; - } - - rotate(alpha, x, y, z) { - this.mult(bg.Matrix4.Rotation(alpha, x, y, z)); - return this; - } - - scale(x, y, z) { - this.mult(bg.Matrix4.Scale(x, y, z)); - return this; - } - - elemAtIndex(i) { return this._m[i]; } - - assign(a) { - if (a.length==9) { - this._m[0] = a._m[0]; this._m[1] = a._m[1]; this._m[2] = a._m[2]; this._m[3] = 0; - this._m[4] = a._m[3]; this._m[5] = a._m[4]; this._m[6] = a._m[5]; this._m[7] = 0; - this._m[8] = a._m[6]; this._m[9] = a._m[7]; this._m[10] = a._m[8]; this._m[11] = 0; - this._m[12] = 0; this._m[13] = 0; this._m[14] = 0; this._m[15] = 1; - } - else if (a.length==16) { - this._m[0] = a._m[0]; this._m[1] = a._m[1]; this._m[2] = a._m[2]; this._m[3] = a._m[3]; - this._m[4] = a._m[4]; this._m[5] = a._m[5]; this._m[6] = a._m[6]; this._m[7] = a._m[7]; - this._m[8] = a._m[8]; this._m[9] = a._m[9]; this._m[10] = a._m[10]; this._m[11] = a._m[11]; - this._m[12] = a._m[12]; this._m[13] = a._m[13]; this._m[14] = a._m[14]; this._m[15] = a._m[15]; - } - return this; - } - - equals(m) { - return this._m[ 0]==m._m[ 0] && this._m[ 1]==m._m[ 1] && this._m[ 2]==m._m[ 2] && this._m[ 3]==m._m[ 3] && - this._m[ 4]==m._m[ 4] && this._m[ 5]==m._m[ 5] && this._m[ 6]==m._m[ 6] && this._m[ 7]==m._m[ 7] && - this._m[ 8]==m._m[ 8] && this._m[ 9]==m._m[ 9] && this._m[10]==m._m[10] && this._m[11]==m._m[11] && - this._m[12]==m._m[12] && this._m[13]==m._m[13] && this._m[14]==m._m[14] && this._m[15]==m._m[15]; - } - - notEquals(m) { - return this._m[ 0]!=m._m[ 0] || this._m[ 1]!=m._m[ 1] || this._m[ 2]!=m._m[ 2] || this._m[ 3]!=m._m[ 3] || - this._m[ 4]!=m._m[ 4] || this._m[ 5]!=m._m[ 5] || this._m[ 6]!=m._m[ 6] || this._m[ 7]!=m._m[ 7] || - this._m[ 8]!=m._m[ 8] || this._m[ 9]!=m._m[ 9] || this._m[10]!=m._m[10] || this._m[11]!=m._m[11] || - this._m[12]!=m._m[12] || this._m[13]!=m._m[13] || this._m[14]!=m._m[14] || this._m[15]!=m._m[15]; - } - - mult(a) { - if (typeof(a)=='number') { - this._m[ 0] *= a; this._m[ 1] *= a; this._m[ 2] *= a; this._m[ 3] *= a; - this._m[ 4] *= a; this._m[ 5] *= a; this._m[ 6] *= a; this._m[ 7] *= a; - this._m[ 8] *= a; this._m[ 9] *= a; this._m[10] *= a; this._m[11] *= a; - this._m[12] *= a; this._m[13] *= a; this._m[14] *= a; this._m[15] *= a; - return this; - } - - var rm = this._m; - var lm = a._m; - var res = new bg.Math.Array(16); - - res[0] = lm[ 0] * rm[ 0] + lm[ 1] * rm[ 4] + lm[ 2] * rm[ 8] + lm[ 3] * rm[12]; - res[1] = lm[ 0] * rm[ 1] + lm[ 1] * rm[ 5] + lm[ 2] * rm[ 9] + lm[ 3] * rm[13]; - res[2] = lm[ 0] * rm[ 2] + lm[ 1] * rm[ 6] + lm[ 2] * rm[10] + lm[ 3] * rm[14]; - res[3] = lm[ 0] * rm[ 3] + lm[ 1] * rm[ 7] + lm[ 2] * rm[11] + lm[ 3] * rm[15]; - - res[4] = lm[ 4] * rm[ 0] + lm[ 5] * rm[ 4] + lm[ 6] * rm[ 8] + lm[ 7] * rm[12]; - res[5] = lm[ 4] * rm[ 1] + lm[ 5] * rm[ 5] + lm[ 6] * rm[ 9] + lm[ 7] * rm[13]; - res[6] = lm[ 4] * rm[ 2] + lm[ 5] * rm[ 6] + lm[ 6] * rm[10] + lm[ 7] * rm[14]; - res[7] = lm[ 4] * rm[ 3] + lm[ 5] * rm[ 7] + lm[ 6] * rm[11] + lm[ 7] * rm[15]; - - res[8] = lm[ 8] * rm[ 0] + lm[ 9] * rm[ 4] + lm[10] * rm[ 8] + lm[11] * rm[12]; - res[9] = lm[ 8] * rm[ 1] + lm[ 9] * rm[ 5] + lm[10] * rm[ 9] + lm[11] * rm[13]; - res[10] = lm[ 8] * rm[ 2] + lm[ 9] * rm[ 6] + lm[10] * rm[10] + lm[11] * rm[14]; - res[11] = lm[ 8] * rm[ 3] + lm[ 9] * rm[ 7] + lm[10] * rm[11] + lm[11] * rm[15]; - - res[12] = lm[12] * rm[ 0] + lm[13] * rm[ 4] + lm[14] * rm[ 8] + lm[15] * rm[12]; - res[13] = lm[12] * rm[ 1] + lm[13] * rm[ 5] + lm[14] * rm[ 9] + lm[15] * rm[13]; - res[14] = lm[12] * rm[ 2] + lm[13] * rm[ 6] + lm[14] * rm[10] + lm[15] * rm[14]; - res[15] = lm[12] * rm[ 3] + lm[13] * rm[ 7] + lm[14] * rm[11] + lm[15] * rm[15]; - - this._m = res; - return this; - } - - multVector(vec) { - if (typeof(vec)=='object' && vec._v && vec._v.length>=3) { - vec = vec._v; - } - let x=vec[0]; - let y=vec[1]; - let z=vec[2]; - let w=1.0; - - return new bg.Vector4(this._m[0]*x + this._m[4]*y + this._m[ 8]*z + this._m[12]*w, - this._m[1]*x + this._m[5]*y + this._m[ 9]*z + this._m[13]*w, - this._m[2]*x + this._m[6]*y + this._m[10]*z + this._m[14]*w, - this._m[3]*x + this._m[7]*y + this._m[11]*z + this._m[15]*w); - } - - invert() { - let a00 = this._m[0], a01 = this._m[1], a02 = this._m[2], a03 = this._m[3], - a10 = this._m[4], a11 = this._m[5], a12 = this._m[6], a13 = this._m[7], - a20 = this._m[8], a21 = this._m[9], a22 = this._m[10], a23 = this._m[11], - a30 = this._m[12], a31 = this._m[13], a32 = this._m[14], a33 = this._m[15]; - - let b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32; - - let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) { - this.zero(); - return this; - } - else { - det = 1.0 / det; - - this._m[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - this._m[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - this._m[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - this._m[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - this._m[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - this._m[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - this._m[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - this._m[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - this._m[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - this._m[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - this._m[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - this._m[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - this._m[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - this._m[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - this._m[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - this._m[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - return this; - } - } - - traspose() { - let r0 = new bg.Vector4(this._m[0], this._m[4], this._m[ 8], this._m[12]); - let r1 = new bg.Vector4(this._m[1], this._m[5], this._m[ 9], this._m[13]); - let r2 = new bg.Vector4(this._m[2], this._m[6], this._m[10], this._m[14]); - let r3 = new bg.Vector4(this._m[3], this._m[7], this._m[11], this._m[15]); - - this.setRow(0, r0); - this.setRow(1, r1); - this.setRow(2, r2); - this.setRow(3, r3); - return this; - } - - transformDirection(/* Vector3 */ dir) { - let direction = new bg.Vector3(dir); - let trx = new bg.Matrix4(this); - trx.setRow(3, new bg.Vector4(0.0, 0.0, 0.0, 1.0)); - direction.assign(trx.multVector(direction).xyz); - direction.normalize(); - return direction; - } - - get forwardVector() { - return this.transformDirection(new bg.Vector3(0.0, 0.0, 1.0)); - } - - get rightVector() { - return this.transformDirection(new bg.Vector3(1.0, 0.0, 0.0)); - } - - get upVector() { - return this.transformDirection(new bg.Vector3(0.0, 1.0, 0.0)); - } - - get backwardVector() { - return this.transformDirection(new bg.Vector3(0.0, 0.0, -1.0)); - } - - get leftVector() { - return this.transformDirection(new bg.Vector3(-1.0, 0.0, 0.0)); - } - - get downVector() { - return this.transformDirection(new bg.Vector3(0.0, -1.0, 0.0)); - } - - isNan() { - return Number.isNaN(this._m[ 0]) || Number.isNaN(this._m[ 1]) || Number.isNaN(this._m[ 2]) || Number.isNaN(this._m[ 3]) || - Number.isNaN(this._m[ 4]) || Number.isNaN(this._m[ 5]) || Number.isNaN(this._m[ 6]) || Number.isNaN(this._m[ 7]) || - Number.isNaN(this._m[ 8]) || Number.isNaN(this._m[ 9]) || Number.isNaN(this._m[10]) || Number.isNaN(this._m[11]) || - Number.isNaN(this._m[12]) || Number.isNaN(this._m[13]) || Number.isNaN(this._m[14]) || Number.isNaN(this._m[15]); - } - - getOrthoValues() { - return [ (1+get23())/get22(), - -(1-get23())/get22(), - (1-get13())/get11(), - -(1+get13())/get11(), - -(1+get03())/get00(), - (1-get03())/get00() ]; - } - - getPerspectiveValues() { - return [ get23()/(get22()-1), - get23()/(get22()+1), - near * (get12()-1)/get11(), - near * (get12()+1)/get11(), - near * (get02()-1)/get00(), - near * (get02()+1)/get00() ]; - } - - toString() { - return "[" + this._m[ 0] + ", " + this._m[ 1] + ", " + this._m[ 2] + ", " + this._m[ 3] + "]\n" + - " [" + this._m[ 4] + ", " + this._m[ 5] + ", " + this._m[ 6] + ", " + this._m[ 7] + "]\n" + - " [" + this._m[ 8] + ", " + this._m[ 9] + ", " + this._m[10] + ", " + this._m[11] + "]\n" + - " [" + this._m[12] + ", " + this._m[13] + ", " + this._m[14] + ", " + this._m[15] + "]"; - } -} - -bg.Matrix4 = Matrix4; - -})(); - -(function() { - class Vector { - static MinComponents(v1,v2) { - let length = Math.min(v1.length, v2.length); - let result = null; - switch (length) { - case 2: - result = new bg.Vector2(); - break; - case 3: - result = new bg.Vector3(); - break; - case 4: - result = new bg.Vector4(); - break; - } - - for (let i=0; iv2._v[i] ? v1._v[i] : v2._v[i]; - } - return result; - } - - constructor(v) { - this._v = v; - } - - get v() { return this._v; } - - get length() { return this._v.length; } - - get x() { return this._v[0]; } - set x(v) { this._v[0] = v; } - get y() { return this._v[1]; } - set y(v) { this._v[1] = v; } - - get module() { return this.magnitude(); } - - toArray() { - let result = []; - for (let i=0; i=2) { - this._v[0] = x[0]; - this._v[1] = x[1]; - } - else { - if (y===undefined) y=x; - this._v[0] = x; - this._v[1] = y; - } - } - - distance(other) { - let v3 = new bg.Vector2(this._v[0] - other._v[0], - this._v[1] - other._v[1]); - return v3.magnitude(); - } - - normalize() { - let m = this.magnitude(); - this._v[0] = this._v[0]/m; this._v[1]=this._v[1]/m; - return this; - } - - add(v2) { - this._v[0] += v2._v[0]; - this._v[1] += v2._v[1]; - return this; - } - - sub(v2) { - this._v[0] -= v2._v[0]; - this._v[1] -= v2._v[1]; - return this; - } - - dot(v2) { - return this._v[0] * v2._v[0] + this._v[1] * v2._v[1]; - } - - scale(scale) { - this._v[0] *= scale; this._v[1] *= scale; - return this; - } - - magnitude() { - return Math.sqrt( - this._v[0] * this._v[0] + - this._v[1] * this._v[1] - ) - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; } - - set(x, y) { - if (y===undefined) y = x; - this._v[0] = x; this._v[1] = y; - } - - get width() { return this._v[0]; } - get height() { return this._v[1]; } - set width(v) { this._v[0] = v; } - set height(v) { this._v[1] = v; } - - get aspectRatio() { return this._v[0]/this._v[1]; } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]); } - - toString() { - return "[" + this._v + "]"; - } - } - - bg.Vector2 = Vector2; - - class Vector3 extends Vector { - static Add(v1,v2) { - return new Vector3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); - } - - static Sub(v1,v2) { - return new Vector3(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); - } - - constructor(x = 0, y = 0, z = 0) { - super(new bg.Math.ArrayHighP(3)); - if (x instanceof Vector2) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = y; - } - else if (x instanceof Vector3) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = x._v[2]; - } - else if (Array.isArray(x) && x.length>=3) { - this._v[0] = x[0]; - this._v[1] = x[1]; - this._v[2] = x[2]; - } - else { - if (y===undefined) y=x; - if (z===undefined) z=y; - this._v[0] = x; - this._v[1] = y; - this._v[2] = z; - } - } - - get z() { return this._v[2]; } - set z(v) { this._v[2] = v; } - - magnitude() { - return Math.sqrt( - this._v[0] * this._v[0] + - this._v[1] * this._v[1] + - this._v[2] * this._v[2] - ); - } - - normalize() { - let m = this.magnitude(); - this._v[0] = this._v[0]/m; this._v[1]=this._v[1]/m; this._v[2]=this._v[2]/m; - return this; - } - - distance(other) { - let v3 = new bg.Vector3(this._v[0] - other._v[0], - this._v[1] - other._v[1], - this._v[2] - other._v[2]); - return v3.magnitude(); - } - - add(v2) { - this._v[0] += v2._v[0]; - this._v[1] += v2._v[1]; - this._v[2] += v2._v[2]; - return this; - } - - sub(v2) { - this._v[0] -= v2._v[0]; - this._v[1] -= v2._v[1]; - this._v[2] -= v2._v[2]; - return this; - } - - dot(v2) { - return this._v[0] * v2._v[0] + this._v[1] * v2._v[1] + this._v[2] * v2._v[2]; - } - - scale(scale) { - this._v[0] *= scale; this._v[1] *= scale; this._v[2] *= scale; - return this; - } - - cross(/* Vector3 */ v2) { - let x = this._v[1] * v2._v[2] - this._v[2] * v2._v[1]; - let y = this._v[2] * v2._v[0] - this._v[0] * v2._v[2]; - let z = this._v[0] * v2._v[1] - this._v[1] * v2._v[0]; - this._v[0]=x; this._v[1]=y; this._v[2]=z; - return this; - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1] && this._v[2]==v._v[2]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1] || this._v[2]!=v._v[2]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; if (v._v.length>=3) this._v[2]=v._v[2]; } - - set(x, y, z) { - this._v[0] = x; - this._v[1] = (y===undefined) ? x:y; - this._v[2] = (y===undefined) ? x:(z===undefined ? y:z); - } - - get width() { return this._v[0]; } - get height() { return this._v[1]; } - get depth() { return this._v[2]; } - - set width(v) { this._v[0] = v; } - set height(v) { this._v[1] = v; } - set depth(v) { this._v[2] = v; } - - get xy() { return new bg.Vector2(this._v[0],this._v[1]); } - get yz() { return new bg.Vector2(this._v[1],this._v[2]); } - get xz() { return new bg.Vector2(this._v[0],this._v[2]); } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]) || isNaN(this._v[2]); } - - toString() { - return "[" + this._v + "]"; - } - } - - bg.Vector3 = Vector3; - - class Vector4 extends Vector { - static Add(v1,v2) { - return new Vector4(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z, v1.w + v2.w); - } - - static Sub(v1,v2) { - return new Vector4(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z, v1.w - v2.w); - } - - static Yellow() { return new bg.Vector4(1.0,1.0,0.0,1.0); } - static Orange() { return new bg.Vector4(1.0,0.5,0.0,1.0); } - static Red() { return new bg.Vector4(1.0,0.0,0.0,1.0); } - static Violet() { return new bg.Vector4(0.5,0.0,1.0,1.0); } - static Blue() { return new bg.Vector4(0.0,0.0,1.0,1.0); } - static Green() { return new bg.Vector4(0.0,1.0,0.0,1.0); } - static White() { return new bg.Vector4(1.0,1.0,1.0,1.0); } - static LightGray() { return new bg.Vector4(0.8,0.8,0.8,1.0); } - static Gray() { return new bg.Vector4(0.5,0.5,0.5,1.0); } - static DarkGray() { return new bg.Vector4(0.2,0.2,0.2,1.0); } - static Black() { return new bg.Vector4(0.0,0.0,0.0,1.0); } - static Brown() { return new bg.Vector4(0.4,0.2,0.0,1.0); } - static Transparent() { return new bg.Vector4(0,0,0,0); } - - constructor(x = 0, y = 0, z = 0, w = 0) { - super(new bg.Math.ArrayHighP(4)); - if (x instanceof Vector2) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = y - this._v[3] = z; - } - else if (x instanceof Vector3) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = x._v[2]; - this._v[3] = y; - } - else if (x instanceof Vector4) { - this._v[0] = x._v[0]; - this._v[1] = x._v[1]; - this._v[2] = x._v[2]; - this._v[3] = x._v[3]; - } - else if (Array.isArray(x) && x.length>=4) { - this._v[0] = x[0]; - this._v[1] = x[1]; - this._v[2] = x[2]; - this._v[3] = x[3]; - } - else { - if (y===undefined) y=x; - if (z===undefined) z=y; - if (w===undefined) w=z; - this._v[0] = x; - this._v[1] = y; - this._v[2] = z; - this._v[3] = w; - } - } - - get z() { return this._v[2]; } - set z(v) { this._v[2] = v; } - get w() { return this._v[3]; } - set w(v) { this._v[3] = v; } - - magnitude() { - return Math.sqrt( - this._v[0] * this._v[0] + - this._v[1] * this._v[1] + - this._v[2] * this._v[2] + - this._v[3] * this._v[3] - ); - } - - normalize() { - let m = this.magnitude(); - this._v[0] = this._v[0]/m; - this._v[1]=this._v[1]/m; - this._v[2]=this._v[2]/m; - this._v[3]=this._v[3]/m; - return this; - } - - distance(other) { - let v3 = new bg.Vector4(this._v[0] - other._v[0], - this._v[1] - other._v[1], - this._v[2] - other._v[2], - this._v[3] - other._v[3]); - return v3.magnitude(); - } - - add(v2) { - this._v[0] += v2._v[0]; - this._v[1] += v2._v[1]; - this._v[2] += v2._v[2]; - this._v[3] += v2._v[3]; - return this; - } - - sub(v2) { - this._v[0] -= v2._v[0]; - this._v[1] -= v2._v[1]; - this._v[2] -= v2._v[2]; - this._v[3] -= v2._v[3]; - return this; - } - - dot(v2) { - return this._v[0] * v2._v[0] + this._v[1] * v2._v[1] + this._v[2] * v2._v[2] + this._v[3] * v2._v[3]; - } - - scale(scale) { - this._v[0] *= scale; this._v[1] *= scale; this._v[2] *= scale; this._v[3] *= scale; - return this; - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1] && this._v[2]==v._v[2] && this._v[3]==v._v[3]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1] || this._v[2]!=v._v[2] || this._v[3]!=v._v[3]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; if (v._v.length>=3) this._v[2]=v._v[2]; if (v._v.length==4) this._v[3]=v._v[3]; } - - set(x, y, z, w) { - this._v[0] = x; - this._v[1] = (y===undefined) ? x:y; - this._v[2] = (y===undefined) ? x:(z===undefined ? y:z); - this._v[3] = (y===undefined) ? x:(z===undefined ? y:(w===undefined ? z:w)); - } - - get r() { return this._v[0]; } - get g() { return this._v[1]; } - get b() { return this._v[2]; } - get a() { return this._v[3]; } - - set r(v) { this._v[0] = v; } - set g(v) { this._v[1] = v; } - set b(v) { this._v[2] = v; } - set a(v) { this._v[3] = v; } - - get xy() { return new bg.Vector2(this._v[0],this._v[1]); } - get yz() { return new bg.Vector2(this._v[1],this._v[2]); } - get xz() { return new bg.Vector2(this._v[0],this._v[2]); } - get xyz() { return new bg.Vector3(this._v[0],this._v[1],this._v[2]); } - - get width() { return this._v[2]; } - get height() { return this._v[3]; } - - set width(v) { this._v[2] = v; } - set height(v) { this._v[3] = v; } - - get aspectRatio() { return this._v[3]!=0 ? this._v[2]/this._v[3]:1.0; } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]) || isNaN(this._v[2]) || isNaN(this._v[3]); } - - toString() { - return "[" + this._v + "]"; - } - } - - bg.Vector4 = Vector4; - - bg.Size2D = Vector2; - bg.Size3D = Vector3; - bg.Position2D = Vector2; - bg.Viewport = Vector4; - bg.Color = Vector4; - - class Bounds extends Vector { - constructor(a=0,b=0,c=0,d=0,e=0,f=0) { - super(new bg.Math.Array(6)); - this._v[0] = a; - this._v[1] = b; - this._v[2] = c; - this._v[3] = d; - this._v[4] = e; - this._v[5] = f; - } - - elemAtIndex(i) { return this._v[i]; } - equals(v) { return this._v[0]==v._v[0] && this._v[1]==v._v[1] && this._v[2]==v._v[2] && this._v[3]==v._v[3] && this._v[4]==v._v[4] && this._v[5]==v._v[5]; } - notEquals(v) { return this._v[0]!=v._v[0] || this._v[1]!=v._v[1] || this._v[2]!=v._v[2] || this._v[3]!=v._v[3] || this._v[4]!=v._v[4] || this._v[5]!=v._v[5]; } - assign(v) { this._v[0]=v._v[0]; this._v[1]=v._v[1]; this._v[2]=v._v[2]; this._v[3]=v._v[3]; this._v[4]=v._v[4]; this._v[5]=v._v[5]; } - - set(left, right, bottom, top, back, front) { - this._v[0] = left; - this._v[1] = (right===undefined) ? left:right; - this._v[2] = (right===undefined) ? left:bottom; - this._v[3] = (right===undefined) ? left:top; - this._v[4] = (right===undefined) ? left:back; - this._v[5] = (right===undefined) ? left:front; - } - - get left() { return this._v[0]; } - get right() { return this._v[1]; } - get bottom() { return this._v[2]; } - get top() { return this._v[3]; } - get back() { return this._v[4]; } - get front() { return this._v[5]; } - - set left(v) { this._v[0] = v; } - set right(v) { this._v[1] = v; } - set bottom(v) { this._v[2] = v; } - set top(v) { this._v[3] = v; } - set back(v) { this._v[4] = v; } - set front(v) { this._v[5] = v; } - - get width() { return Math.abs(this._v[1] - this._v[0]); } - get height() { return Math.abs(this._v[3] - this._v[2]); } - get depth() { return Math.abs(this._v[5] - this._v[4]); } - - isNan() { return isNaN(this._v[0]) || isNaN(this._v[1]) || isNaN(this._v[2]) || isNaN(this._v[3]) || isNaN(this._v[4]) || isNaN(this._v[5]); } - - toString() { - return "[" + this._v + "]"; - } - - isInBounds(/* vwgl.Vector3*/ v) { - return v.x>=this._v[0] && v.x<=this._v[1] && - v.y>=this._v[2] && v.y<=this._v[3] && - v.z>=this._v[4] && v.z<=this._v[5]; - } - } - - bg.Bounds = Bounds; - - class Quaternion extends Vector4 { - static MakeWithMatrix(m) { - return new Quaternion(m); - } - - constructor(a,b,c,d) { - super(); - if (a===undefined) this.zero(); - else if (b===undefined) { - if (a._v && a._v.lenght>=4) this.clone(a); - else if(a._m && a._m.length==9) this.initWithMatrix3(a); - else if(a._m && a._m.length==16) this.initWithMatrix4(a); - else this.zero(); - } - else if (a!==undefined && b!==undefined && c!==undefined && d!==undefined) { - this.initWithValues(a,b,c,d); - } - else { - this.zero(); - } - } - - initWithValues(alpha,x,y,z) { - this._v[0] = x * bg.Math.sin(alpha/2); - this._v[1] = y * bg.Math.sin(alpha/2); - this._v[2] = z * bg.Math.sin(alpha/2); - this._v[3] = bg.Math.cos(alpha/2); - return this; - } - - clone(q) { - this._v[0] = q._v[0]; - this._v[1] = q._v[1]; - this._v[2] = q._v[2]; - this._v[3] = q._v[3]; - } - - initWithMatrix3(m) { - let w = bg.Math.sqrt(1.0 + m._m[0] + m._m[4] + m._m[8]) / 2.0; - let w4 = 4.0 * w; - - this._v[0] = (m._m[7] - m._m[5]) / w; - this._v[1] = (m._m[2] - m._m[6]) / w4; - this._v[2] = (m._m[3] - m._m[1]) / w4; - this._v[3] = w; - } - - initWithMatrix4(m) { - let w = bg.Math.sqrt(1.0 + m._m[0] + m._m[5] + m._m[10]) / 2.0; - let w4 = 4.0 * w; - - this._v[0] = (m._m[9] - m._m[6]) / w; - this._v[1] = (m._m[2] - m._m[8]) / w4; - this._v[2] = (m._m[4] - m._m[1]) / w4; - this._v[3] = w; - } - - getMatrix4() { - let m = bg.Matrix4.Identity(); - let _v = this._v; - m.setRow(0, new bg.Vector4(1.0 - 2.0*_v[1]*_v[1] - 2.0*_v[2]*_v[2], 2.0*_v[0]*_v[1] - 2.0*_v[2]*_v[3], 2.0*_v[0]*_v[2] + 2.0*_v[1]*_v[3], 0.0)); - m.setRow(1, new bg.Vector4(2.0*_v[0]*_v[1] + 2.0*_v[2]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[2]*_v[2], 2.0*_v[1]*_v[2] - 2.0*_v[0]*_v[3], 0.0)); - m.setRow(2, new bg.Vector4(2.0*_v[0]*_v[2] - 2.0*_v[1]*_v[3], 2.0*_v[1]*_v[2] + 2.0*_v[0]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[1]*_v[1], 0.0)); - return m; - } - - getMatrix3() { - let m = bg.Matrix3.Identity(); - let _v = this._v; - - m.setRow(0, new bg.Vector3(1.0 - 2.0*_v[1]*_v[1] - 2.0*_v[2]*_v[2], 2.0*_v[0]*_v[1] - 2.0*_v[2]*_v[3], 2.0*_v[0]*_v[2] + 2.0*_v[1]*_v[3])); - m.setRow(1, new bg.Vector3(2.0*_v[0]*_v[1] + 2.0*_v[2]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[2]*_v[2], 2.0*_v[1]*_v[2] - 2.0*_v[0]*_v[3])); - m.setRow(2, new bg.Vector3(2.0*_v[0]*_v[2] - 2.0*_v[1]*_v[3], 2.0*_v[1]*_v[2] + 2.0*_v[0]*_v[3], 1.0 - 2.0*_v[0]*_v[0] - 2.0*_v[1]*_v[1])); - return m; - } - } - - bg.Quaternion = Quaternion; - -})(); - -bg.physics = {}; -(function() { - - bg.physics.IntersectionType = { - NONE:0, - POINT:1, - LLINE:2 - }; - - class Intersection { - - static RayToPlane(ray,plane) { - return new bg.physics.RayToPlaneIntersection(ray,plane); - } - - constructor() { - this._type = null; - this._p0 = null; - this._p1 = null; - } - - get type() { return this._type; } - get point() { return this._p0; } - get endPoint() { return this._p1; } - - intersects() { return false; } - } - - bg.physics.Intersection = Intersection; - - class RayToPlaneIntersection extends bg.physics.Intersection { - constructor(ray,plane) { - super(); - this._ray = null; - this._p0 = null; - - this._type = bg.physics.IntersectionType.POINT; - let p0 = new bg.Vector3(plane.origin); - let n = new bg.Vector3(plane.normal); - let l0 = new bg.Vector3(ray.start); - let l = new bg.Vector3(ray.vector); - let num = p0.sub(l0).dot(n); - let den = l.dot(n); - - if (den==0) return; - let d = num/den; - if (d>ray.magnitude) return; - - this._ray = bg.physics.Ray.RayWithVector(ray.vector,ray.start,d); - this._p0 = this._ray.end; - } - - get ray() { - return this._ray; - } - - intersects() { - return (this._ray!=null && this._p0!=null); - } - } - - bg.physics.RayToPlaneIntersection = RayToPlaneIntersection; - - -})(); -(function() { - - class Joint { - static Factory(linkData) { - switch (linkData.type) { - case 'LinkJoint': - return LinkJoint.Factory(linkData); - break; - } - return null; - } - - constructor() { - this._transform = bg.Matrix4.Identity(); - } - - get transform() { return this._transform; } - set transform(t) { this._transform = t; } - - applyTransform(matrix) { - - } - - calculateTransform() { - - } - } - - bg.physics.Joint = Joint; - - bg.physics.LinkTransformOrder = { - TRANSLATE_ROTATE:1, - ROTATE_TRANSLATE:0 - } - - class LinkJoint extends Joint { - static Factory(data) { - let result = new LinkJoint(); - result.offset = new bg.Vector3( - data.offset[0] || 0, - data.offset[1] || 0, - data.offset[2] || 0 - ); - result.yaw = data.yaw || 0; - result.pitch = data.pitch || 0; - result.roll = data.roll || 0; - result.order = data.order || 1; - return result; - } - - constructor() { - super(); - this._offset = new bg.Vector3(); - this._eulerRotation = new bg.Vector3(); - - this._transformOrder = bg.physics.LinkTransformOrder.TRANSLATE_ROTATE; - } - - applyTransform(matrix) { - matrix.mult(this.transform); - } - - assign(j) { - this.yaw = j.yaw; - this.pitch = j.pitch; - this.roll = j.roll; - this.offset.assign(j.offset); - this.transformOrder = j.transformOrder; - } - - get offset() { return this._offset; } - set offset(o) { this._offset = o; this.calculateTransform(); } - - get eulerRotation() { return this._eulerRotation; } - set eulerRotation(r) { this._eulerRotation = r; this.calculateTransform(); } - - get yaw() { return this._eulerRotation.x; } - get pitch() { return this._eulerRotation.y; } - get roll() { return this._eulerRotation.z; } - - set yaw(y) { this._eulerRotation.x = y; this.calculateTransform(); } - set pitch(p) { this._eulerRotation.y = p; this.calculateTransform(); } - set roll(r) { this._eulerRotation.z = r; this.calculateTransform(); } - - get transformOrder() { return this._transformOrder; } - set transformOrder(o) { this._transformOrder = o; this.calculateTransform(); } - - multTransform(dst) { - let offset = this.offset; - switch (this.transformOrder) { - case bg.physics.LinkTransformOrder.TRANSLATE_ROTATE: - dst.translate(offset.x,offset.y,offset.z); - this.multRotation(dst); - break; - case bg.physics.LinkTransformOrder.ROTATE_TRANSLATE: - this.multRotation(dst); - dst.translate(offset.x,offset.y,offset.z); - break; - } - } - - multRotation(dst) { - dst.rotate(this.eulerRotation.z, 0,0,1) - .rotate(this.eulerRotation.y, 0,1,0) - .rotate(this.eulerRotation.x, 1,0,0); - } - - calculateTransform() { - this.transform.identity(); - this.multTransform(this.transform); - } - - serialize(data) { - data.type = "LinkJoint"; - data.offset = [ - this.offset.x, - this.offset.y, - this.offset.z - ]; - data.yaw = this.yaw; - data.pitch = this.pitch; - data.roll = this.roll; - data.order = this.order; - } - } - - bg.physics.LinkJoint = LinkJoint; -})(); -(function() { - - class Plane { - // a = normal: create a plane with origin=(0,0,0) and normal=a - // a = normal, b = origin: create a plane with origin=b and normal=a - // a = p1, b = p2, c = p3: create a plane that contains the points p1, p2 and p3 - constructor(a, b, c) { - a = a instanceof bg.Vector3 && a; - b = b instanceof bg.Vector3 && b; - c = c instanceof bg.Vector3 && c; - if (a && !b) { - this._normal = new bg.Vector3(a); - this._origin = new bg.Vector3(0); - } - else if (a && b && !c) { - this._normal = new bg.Vector3(a); - this._origin = new bg.Vector3(b); - } - else if (a && b && c) { - var vec1 = new bg.Vector3(a); vec1.sub(b); - var vec2 = new bg.Vector3(c); vec2.sub(a); - this._origin = new bg.Vector3(p1); - this._normal = new bg.Vector3(vec1); - this._normal.cross(vec2).normalize(); - } - else { - this._origin = new bg.Vector3(0); - this._normal = new bg.Vector3(0,1,0); - } - } - - get normal() { return this._normal; } - set normal(n) { this._normal.assign(n); } - - get origin() { return this._origin; } - set origin(o) { this._origin.assign(o); } - - toString() { - return `P0: ${this._origin.toString()}, normal:${this._normal.toString()}`; - } - - valid() { return !this._origin.isNan() && !this._normal.isNan(); } - - assign(p) { - this._origin.assign(p._origin); - this._normal.assign(p._normal); - return this; - } - - equals(p) { - return this._origin.equals(p._origin) && this._normal.equals(p._normal); - } - } - - bg.physics.Plane = Plane; - -})(); -(function() { - - function calculateVector(ray) { - ray._vector = new bg.Vector3(ray._end); - ray._vector.sub(ray._start); - ray._magnitude = ray._vector.magnitude(); - ray._vector.normalize(); - } - - class Ray { - static RayWithPoints(start,end) { - return new Ray(start,end); - } - - static RayWithVector(vec,origin,maxDepth) { - let r = new Ray(); - r.setWithVector(vec,origin,maxDepth); - return r; - } - - static RayWithScreenPoint(screenPoint,projMatrix,viewMatrix,viewport) { - let r = new Ray(); - r.setWithScreenPoint(screenPoint,projMatrix,viewMatrix,viewport); - return r; - } - - - constructor(start,end) { - this._start = start || new bg.Vector3(); - this._end = end || new bg.Vector3(1); - calculateVector(this); - } - - setWithPoints(start,end) { - this._start.assign(start); - this._end.assign(end); - calculateVector(); - return this; - } - - setWithVector(vec,origin,maxDepth) { - this._start.assign(origin); - this._end.assign(origin); - let vector = new bg.Vector3(vec); - vector.normalize().scale(maxDepth); - this._end.add(vector); - calculateVector(this); - return this; - } - - setWithScreenPoint(screenPoint,projMatrix,viewMatrix,viewport) { - let start = bg.Matrix4.Unproject(screenPoint.x, screenPoint.y, 0, viewMatrix, projMatrix, viewport); - let end = bg.Matrix4.Unproject(screenPoint.x, screenPoint.y, 1, viewMatrix, projMatrix, viewport); - this._start = start.xyz; - this._end = end.xyz; - calculateVector(this); - return this; - } - - assign(r) { - this._start.assign(r.start); - this._end.assign(r.end); - this._vector.assign(r.vector); - this._magnitude.assign(r.magnitude); - } - - get start() { return this._start; } - set start(s) { this._start.assign(s); calculateVector(this); } - - get end() { return this._end; } - set end(e) { this._end.assign(e); } - - get vector() { return this._vector; } - - get magnitude() { return this._magnitude; } - - toString() { - return `start: ${this.start.toString()}, end: ${this.end.toString()}`; - } - } - - bg.physics.Ray = Ray; - -})() - -bg.scene = {}; - -(function() { - - let s_componentRegister = {}; - - class Component extends bg.LifeCycle { - static Factory(context,componentData,node,url) { - let Constructor = s_componentRegister[componentData.type]; - if (Constructor) { - let instance = new Constructor(); - node.addComponent(instance); - return instance.deserialize(context,componentData,url); - } - else { - return Promise.resolve(); - } - - } - - constructor() { - super(); - - this._node = null; - - this._drawGizmo = true; - } - - clone() { - bg.log(`WARNING: Component with typeid ${this.typeId} does not implmement the clone() method.`); - return null; - } - - destroy() { - - } - - get node() { return this._node; } - - get typeId() { return this._typeId; } - - get draw3DGizmo() { return this._drawGizmo; } - set draw3DGizmo(d) { this._drawGizmo = d; } - - removedFromNode(node) {} - addedToNode(node) {} - - // Override this to prevent serialize this component - get shouldSerialize() { return true; } - - deserialize(context,sceneData,url) { - return Promise.resolve(this); - } - - // componentData: the current json object corresponding to the parent node - // promises: array of promises. If the component needs to execute asynchronous - // actions, it can push one or more promises into this array - // url: the destination scene url, composed by: - // { - // path: "scene path, using / as separator even on Windows", - // fileName: "scene file name" - // } - serialize(componentData,promises,url) { - componentData.type = this.typeId.split(".").pop(); - } - - // The following functions are implemented in the SceneComponent class, in the C++ API - component(typeId) { return this._node && this._node.component(typeId); } - - get camera() { return this.component("bg.scene.Camera"); } - get chain() { return this.component("bg.scene.Chain"); } - get drawable() { return this.component("bg.scene.Drawable"); } - get inputChainJoint() { return this.component("bg.scene.InputChainJoint"); } - get outputChainJoint() { return this.component("bg.scene.OutputChainJoint"); } - get light() { return this.component("bg.scene.Light"); } - get transform() { return this.component("bg.scene.Transform"); } - } - - bg.scene.Component = Component; - - bg.scene.registerComponent = function(namespace,componentClass,identifier) { - let result = /function (.+)\(/.exec(componentClass.toString()); - if (!result) { - result = /class ([a-zA-Z0-9_]+) /.exec(componentClass.toString()); - } - let funcName = (result && result.length>1) ? result[1] : ""; - - namespace[funcName] = componentClass; - componentClass.prototype._typeId = identifier || funcName; - - - s_componentRegister[funcName] = componentClass; - } - -})(); -(function() { - class SceneObjectLifeCycle extends bg.LifeCycle { - // This class reimplements the bg.app.ContextObject due to the lack - // in JavaScript of multiple ihneritance - - constructor(context) { - super(context); - - this._context = context; - } - - get context() { return this._context; } - set context(c) { this._context = c; } - } - - function updateComponentsArray() { - this._componentsArray = []; - for (let key in this._components) { - this._components[key] && this._componentsArray.push(this._components[key]); - } - } - - class SceneObject extends SceneObjectLifeCycle { - - constructor(context,name="") { - super(context); - - this._name = name; - this._enabled = true; - this._steady = false; - - this._components = {}; - this._componentsArray = []; - } - - toString() { - return " scene object: " + this._name; - } - - // Create a new instance of this node, with a copy of all it's components - cloneComponents() { - let newNode = new bg.scene.Node(this.context,this.name ? `copy of ${this.name}`:""); - newNode.enabled = this.enabled; - this.forEachComponent((comp) => { - newNode.addComponent(comp.clone()); - }); - return newNode; - } - - get name() { return this._name; } - set name(n) { this._name = n; } - - get enabled() { return this._enabled; } - set enabled(e) { this._enabled = e; } - - get steady() { return this._steady; } - set steady(s) { this._steady = s; } - - addComponent(c) { - if (c._node) { - c._node.removeComponent(c); - } - c._node = this; - this._components[c.typeId] = c; - c.addedToNode(this); - updateComponentsArray.apply(this); - } - - // It's possible to remove a component by typeId or by the specific object. - // - typeId: if the scene object contains a component of this type, will be removed - // - specific object: if the scene object contains the specified object, will be removed - removeComponent(findComponent) { - let typeId = ""; - let comp = null; - if (typeof(findComponent)=="string") { - typeId = findComponent - comp = this.component(findComponent); - } - else if (findComponent instanceof bg.scene.Component) { - comp = findComponent; - typeId = findComponent.typeId; - } - - let status = false; - if (this._components[typeId]==comp && comp!=null) { - delete this._components[typeId]; - comp.removedFromNode(this); - status = true; - } - - updateComponentsArray.apply(this); - return status; - } - - component(typeId) { - return this._components[typeId]; - } - - // Most common components - get camera() { return this.component("bg.scene.Camera"); } - get chain() { return this.component("bg.scene.Chain"); } - get drawable() { return this.component("bg.scene.Drawable"); } - get inputJoint() { return this.component("bg.scene.InputJoint"); } - get outputJoint() { return this.component("bg.scene.OutputJoint"); } - get light() { return this.component("bg.scene.Light"); } - get transform() { return this.component("bg.scene.Transform"); } - - forEachComponent(callback) { - this._componentsArray.forEach(callback); - } - - someComponent(callback) { - return this._componentsArray.some(callback); - } - - everyComponent(callback) { - return this._componentsArray.every(callback); - } - - destroy() { - this.forEachComponent((comp) => { - comp.removedFromNode(this); - }); - - this._components = {}; - this._componentsArray = []; - } - - init() { - this._componentsArray.forEach((comp) => { - comp.init(); - }); - } - - frame(delta) { - this._componentsArray.forEach((comp) => { - if (!comp._initialized_) { - comp.init(); - comp._initialized_ = true; - } - comp.frame(delta); - }); - } - - displayGizmo(pipeline,matrixState) { - this._componentsArray.forEach((comp) => { - if (comp.draw3DGizmo) comp.displayGizmo(pipeline,matrixState); - }); - } - - /////// Direct rendering methods: will be deprecated soon - willDisplay(pipeline,matrixState) { - this._componentsArray.forEach((comp) => { - comp.willDisplay(pipeline,matrixState); - }); - } - - display(pipeline,matrixState,forceDraw=false) { - this._componentsArray.forEach((comp) => { - comp.display(pipeline,matrixState,forceDraw); - }); - } - - - didDisplay(pipeline,matrixState) { - this._componentsArray.forEach((comp) => { - comp.didDisplay(pipeline,matrixState); - }); - } - //////// End direct rendering methods - - - ////// Render queue methods - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - this._componentsArray.forEach((comp) => { - comp.willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack); - }); - } - - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - this._componentsArray.forEach((comp) => { - comp.draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack); - }); - } - - didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - this._componentsArray.forEach((comp) => { - comp.didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack); - }); - } - ////// End render queue methods - - - reshape(pipeline,matrixState,width,height) { - this._componentsArray.forEach((comp) => { - comp.reshape(width,height); - }); - } - - keyDown(evt) { - this._componentsArray.forEach((comp) => { - comp.keyDown(evt); - }); - } - - keyUp(evt) { - this._componentsArray.forEach((comp) => { - comp.keyUp(evt); - }); - } - - mouseUp(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseUp(evt); - }); - } - - mouseDown(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseDown(evt); - }); - } - - mouseMove(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseMove(evt); - }); - } - - mouseOut(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseOut(evt); - }); - } - - mouseDrag(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseDrag(evt); - }); - } - - mouseWheel(evt) { - this._componentsArray.forEach((comp) => { - comp.mouseWheel(evt); - }); - } - - touchStart(evt) { - this._componentsArray.forEach((comp) => { - comp.touchStart(evt); - }); - } - - touchMove(evt) { - this._componentsArray.forEach((comp) => { - comp.touchMove(evt); - }); - } - - touchEnd(evt) { - this._componentsArray.forEach((comp) => { - comp.touchEnd(evt); - }); - } - } - - bg.scene.SceneObject = SceneObject; - -})(); -(function() { - - function isNodeAncient(node, ancient) { - if (!node || !ancient) { - return false; - } - else if (node._parent==ancient) { - return true; - } - else { - return isNodeAncient(node._parent, ancient); - } - } - - function cleanupNode(sceneNode) { - let components = []; - let children = []; - sceneNode.forEachComponent((c) => components.push(c)); - sceneNode.children.forEach((child) => children.push(child)); - components.forEach((c) => sceneNode.removeComponent(c)); - children.forEach((child) => { - sceneNode.removeChild(child); - cleanupNode(child); - }); - } - - class Node extends bg.scene.SceneObject { - // IMPORTANT: call this function to clean all the resources of - // a node if you don't want to use it anymore. - static CleanupNode(node) { - cleanupNode(node); - } - - constructor(context,name="") { - super(context,name); - - this._children = []; - this._parent = null; - } - - toString() { - return super.toString() + " (" + this._children.length + " children and " + Object.keys(this._components).length + " components)"; - } - - addChild(child) { - if (child && !this.isAncientOf(child) && child!=this) { - if (child.parent) { - child.parent.removeChild(child); - } - this._children.push(child); - child._parent = this; - } - } - - removeChild(node) { - let index = this._children.indexOf(node); - if (index>=0) { - this._children.splice(index,1); - } - } - - get children() { return this._children; } - - get parent() { return this._parent; } - - get sceneRoot() { - if (this._parent) { - return this._parent.sceneRoot(); - } - return this; - } - - haveChild(node) { - return this._children.indexOf(node)!=-1; - } - - isAncientOf(node) { - isNodeAncient(this,node); - } - - accept(nodeVisitor) { - if (!nodeVisitor.ignoreDisabled || this.enabled) { - nodeVisitor.visit(this); - this._children.forEach((child) => { - child.accept(nodeVisitor); - }); - nodeVisitor.didVisit(this); - } - } - - acceptReverse(nodeVisitor) { - if (!nodeVisitor.ignoreDisabled || this.enabled) { - if (this._parent) { - this._parent.acceptReverse(nodeVisitor); - } - nodeVisitor.visit(this); - } - } - - destroy() { - super.destroy(); - this._children.forEach((child) => { - child.destroy(); - }); - this._children = []; - } - - } - - bg.scene.Node = Node; - - class NodeVisitor { - constructor() { - this._ignoreDisabled = true; - } - - get ignoreDisabled() { return this._ignoreDisabled; } - - set ignoreDisabled(v) { this._ignoreDisabled = v; } - - visit(node) {} - didVisit(node) {} - } - - bg.scene.NodeVisitor = NodeVisitor; -})(); -(function() { - - class ProjectionStrategy extends bg.MatrixStrategy { - static Factory(jsonData) { - let result = null; - if (jsonData) { - if (jsonData.type=="PerspectiveProjectionMethod") { - result = new PerspectiveProjectionStrategy(); - } - else if (jsonData.type=="OpticalProjectionMethod") { - result = new OpticalProjectionStrategy(); - } - else if (jsonData.type=="OrthographicProjectionStrategy") { - result = new OrthographicProjectionStrategy(); - } - - if (result) { - result.deserialize(jsonData); - } - } - return result; - } - - constructor(target) { - super(target); - - this._near = 0.1; - this._far = 100.0; - this._viewport = new bg.Viewport(0,0,512,512); - } - - clone() { console.log("WARNING: ProjectionStrategy::clone() method not implemented by child class."); } - - get near() { return this._near; } - set near(n) { this._near = n; } - get far() { return this._far; } - set far(f) { this._far = f; } - get viewport() { return this._viewport; } - set viewport(vp) { this._viewport = vp; } - - get fov() { return 0; } - - serialize(jsonData) { - jsonData.near = this.near; - jsonData.far = this.far; - } - } - - bg.scene.ProjectionStrategy = ProjectionStrategy; - - class PerspectiveProjectionStrategy extends ProjectionStrategy { - constructor(target) { - super(target); - this._fov = 60; - } - - clone() { - let result = new PerspectiveProjectionStrategy(); - result.near = this.near; - result.far = this.far; - result.viewport = this.viewport; - result.fov = this.fov; - return result; - } - - get fov() { return this._fov; } - set fov(f) { this._fov = f; } - - apply() { - if (this.target) { - this.target.perspective(this.fov, this.viewport.aspectRatio, this.near, this.far); - } - } - - deserialize(jsonData) { - this.near = jsonData.near; - this.far = jsonData.far; - this.fov = jsonData.fov; - } - - serialize(jsonData) { - jsonData.type = "PerspectiveProjectionMethod"; - jsonData.fov = this.fov; - super.serialize(jsonData); - } - } - - bg.scene.PerspectiveProjectionStrategy = PerspectiveProjectionStrategy; - - class OpticalProjectionStrategy extends ProjectionStrategy { - constructor(target) { - super(target); - this._focalLength = 50; - this._frameSize = 35; - } - - clone() { - let result = new OpticalProjectionStrategy(); - result.near = this.near; - result.far = this.far; - result.viewport = this.viewport; - result.focalLength = this.focalLength; - result.frameSize = this.frameSize; - return result; - } - - get focalLength() { return this._focalLength; } - set focalLength(fl) { this._focalLength = fl; } - get frameSize() { return this._frameSize; } - set frameSize(s) { this._frameSize = s; } - - get fov() { - return 2 * bg.Math.atan(this.frameSize / (this.focalLength / 2)); - } - - apply() { - if (this.target) { - let fov = this.fov; - fov = bg.Math.radiansToDegrees(fov); - this.target.perspective(fov, this.viewport.aspectRatio, this.near, this.far); - } - } - - deserialize(jsonData) { - this.frameSize = jsonData.frameSize; - this.focalLength = jsonData.focalLength; - this.near = jsonData.near; - this.far = jsonData.far; - } - - serialize(jsonData) { - jsonData.type = "OpticalProjectionMethod"; - jsonData.frameSize = this.frameSize; - jsonData.focalLength = this.focalLength; - super.serialize(jsonData); - } - } - - bg.scene.OpticalProjectionStrategy = OpticalProjectionStrategy; - - class OrthographicProjectionStrategy extends ProjectionStrategy { - constructor(target) { - super(target); - this._viewWidth = 100; - } - - clone() { - let result = new OrthographicProjectionStrategy(); - result.near = this.near; - result.far = this.far; - result.viewWidth = this.viewWidth; - return result; - } - - get viewWidth() { return this._viewWidth; } - set viewWidth(w) { this._viewWidth = w; } - - apply() { - if (this.target) { - let ratio = this.viewport.aspectRatio; - let height = this.viewWidth / ratio; - let x = this.viewWidth / 2; - let y = height / 2; - this.target.ortho(-x, x, -y, y, -this._far, this._far); - } - } - - deserialize(jsonData) { - this.viewWidth = jsonData.viewWidth; - this.near = jsonData.near; - this.far = jsonData.far; - } - - serialize(jsonData) { - jsonData.type = "OrthographicProjectionStrategy"; - jsonData.viewWidth = this.viewWidth; - jsonData.near = this.near; - jsonData.far = this.far; - super.serialize(jsonData); - } - } - - bg.scene.OrthographicProjectionStrategy = OrthographicProjectionStrategy; - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i clearMain(child)); - } - - class Camera extends bg.scene.Component { - - static SetAsMainCamera(mainCamera,sceneRoot) { - clearMain(sceneRoot); - if (mainCamera instanceof Camera) { - mainCamera.isMain = true; - } - else if (mainCamera instanceof bg.scene.Node && mainCamera.camera) { - mainCamera.camera.isMain = true; - } - else { - throw new Error("Error setting main camera: invalid camera node."); - } - } - - constructor() { - super(); - - this._projection = bg.Matrix4.Perspective(60,1,0.1,100.0); - this._viewport = new bg.Viewport(0,0,512,512); - - this._visitor = new bg.scene.TransformVisitor(); - this._rebuildTransform = true; - - this._position = new bg.Vector3(0); - this._rebuildPosition = true; - - this._clearBuffers = bg.base.ClearBuffers.COLOR_DEPTH; - - this._focus = 5; // default 5 meters - - this._projectionStrategy = null; - - this._isMain = false; - } - - clone() { - let newCamera = new bg.scene.Camera(); - newCamera._projection = new bg.Matrix4(this._projection); - newCamera._viewport = new bg.Matrix4(this._viewport); - newCamera._projectionStrategy = this._projectionStrategy ? this._projectionStrategy.clone() : null; - return newCamera; - } - - get projection() { return this._projection; } - set projection(p) { - if (!this._projectionStrategy) { - this._projection = p; - } - } - - get viewport() { return this._viewport; } - set viewport(v) { - this._viewport = v; - if (this._projectionStrategy) { - this._projectionStrategy.viewport = v; - this._projectionStrategy.apply(); - } - } - - get focus() { return this._focus; } - set focus(f) { this._focus = f; this.recalculateGizmo() } - - get isMain() { return this._isMain; } - set isMain(m) { - this._isMain = m; - } - - get projectionStrategy() { return this._projectionStrategy; } - set projectionStrategy(ps) { - this._projectionStrategy = ps; - if (this._projectionStrategy) { - this._projectionStrategy.target = this._projection; - } - this.recalculateGizmo() - } - - get clearBuffers() { return this._clearBuffers; } - set clearBuffers(c) { this._clearBuffers = c; } - - get modelMatrix() { - if (this._rebuildTransform && this.node) { - this._visitor.matrix.identity(); - this.node.acceptReverse(this._visitor); - this._rebuildTransform = false; - } - return this._visitor.matrix; - } - - get viewMatrix() { - if (!this._viewMatrix || this._rebuildTransform) { - this._viewMatrix = new bg.Matrix4(this.modelMatrix); - this._viewMatrix.invert(); - } - return this._viewMatrix; - } - - get worldPosition() { - if (this._rebuildPosition) { - this._position = this.modelMatrix.multVector(new bg.Vector3(0)).xyz - this._rebuildPosition = false; - this._rebuildTransform = true; - } - return this._position; - } - - recalculateGizmo() { - if (this._gizmo) { - this._gizmo.destroy(); - this._gizmo = null; - } - } - - frame(delta) { - this._rebuildPosition = true; - this._rebuildTransform = true; - } - - displayGizmo(pipeline,matrixState) { - if (this.isMain) return; // Do not render the main camera plist - let plist = getGizmo.apply(this); - if (plist) { - pipeline.draw(plist); - } - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.isMain = this.isMain; - if (this.projectionStrategy) { - let projMethod = {}; - componentData.projectionMethod = projMethod; - this.projectionStrategy.serialize(projMethod); - } - } - - deserialize(context,sceneData,url) { - sceneData.isMain = sceneData.isMain || false; - this.projectionStrategy = ProjectionStrategy.Factory(sceneData.projectionMethod || {}); - } - } - - bg.scene.registerComponent(bg.scene,Camera,"bg.scene.Camera"); -})(); -(function() { - - let GizmoType = { - IN_JOINT: 0, - OUT_JOINT: 1 - } - - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i { - let trx = child.component("bg.scene.Transform"); - let inJoint = child.component("bg.scene.InputChainJoint"); - let outJoint = child.component("bg.scene.OutputChainJoint"); - - if (index>0 && inJoint) { - inJoint.joint.applyTransform(matrix); - } - else { - matrix.identity(); - } - - if (trx) { - trx.matrix.assign(matrix); - } - - if (outJoint) { - outJoint.joint.applyTransform(matrix); - } - }); - } - } - - class Chain extends bg.scene.Component { - constructor() { - super(); - } - - clone() { - return new bg.scene.Chain(); - } - - - ////// Direct rendering functions: will be deprecated soon - willDisplay(pipeline,matrixState,projectionMatrixStack) { - updateJointTransforms.apply(this); - } - - ////// Render queue functions - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - updateJointTransforms.apply(this); - } - } - - bg.scene.registerComponent(bg.scene,Chain,"bg.scene.Chain"); - - class ChainJoint extends bg.scene.Component { - constructor() { - super(); - - this._joint = new bg.physics.LinkJoint(); - } - - get joint() { return this._joint; } - set joint(j) { this._joint = j; } - - deserialize(context,sceneData,url) { - if (sceneData.joint) { - this.joint = bg.physics.Joint.Factory(sceneData.joint); - } - } - } - - bg.scene.ChainJoint = ChainJoint; - - class InputChainJoint extends ChainJoint { - constructor(joint) { - super(); - if (joint) { - this.joint = joint; - } - else { - this.joint.transformOrder = bg.physics.LinkTransformOrder.ROTATE_TRANSLATE; - } - } - - clone() { - let newJoint = new bg.scene.InputChainJoint(); - newJoint.joint.assign(this.joint); - return newJoint; - } - - displayGizmo(pipeline,matrixState) { - let plist = getGizmo.apply(this,[0]); - if (plist) { - matrixState.modelMatrixStack.push(); - let mat = new bg.Matrix4(this.joint.transform); - mat.invert(); - matrixState.modelMatrixStack.mult(mat); - pipeline.draw(plist); - matrixState.modelMatrixStack.pop(); - } - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.joint = {}; - this.joint.serialize(componentData.joint); - } - } - - bg.scene.registerComponent(bg.scene,InputChainJoint,"bg.scene.InputChainJoint"); - - - class OutputChainJoint extends ChainJoint { - constructor(joint) { - super(); - if (joint) { - this.joint = joint; - } - else { - this.joint.transformOrder = bg.physics.LinkTransformOrder.TRANSLATE_ROTATE; - } - } - - clone() { - let newJoint = new bg.scene.OutputChainJoint(); - newJoint.joint.assign(this.joint); - return newJoint; - } - - displayGizmo(pipeline,matrixState) { - let plist = getGizmo.apply(this,[1]); - if (plist) { - matrixState.modelMatrixStack.push(); - let mat = new bg.Matrix4(this.joint.transform); - matrixState.modelMatrixStack.mult(mat); - pipeline.draw(plist); - matrixState.modelMatrixStack.pop(); - } - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.joint = {}; - this.joint.serialize(componentData.joint); - } - } - - bg.scene.registerComponent(bg.scene,OutputChainJoint,"bg.scene.OutputChainJoint"); - -})(); -(function() { - bg.scene.CubemapImage = { - POSITIVE_X: 0, - NEGATIVE_X: 1, - POSITIVE_Y: 2, - NEGATIVE_Y: 3, - POSITIVE_Z: 4, - NEGATIVE_Z: 5, - }; - - let g_currentCubemap = null; - - function copyCubemapImage(componentData,cubemapImage,dstPath) { - let path = require("path"); - let src = bg.base.Writer.StandarizePath(this.getImageUrl(cubemapImage)); - let file = src.split('/').pop(); - let dst = bg.base.Writer.StandarizePath(path.join(dstPath,file)); - switch (cubemapImage) { - case bg.scene.CubemapImage.POSITIVE_X: - componentData.positiveX = file; - break; - case bg.scene.CubemapImage.NEGATIVE_X: - componentData.negativeX = file; - break; - case bg.scene.CubemapImage.POSITIVE_Y: - componentData.positiveY = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Y: - componentData.negativeY = file; - break; - case bg.scene.CubemapImage.POSITIVE_Z: - componentData.positiveZ = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Z: - componentData.negativeZ = file; - break; - } - return bg.base.Writer.CopyFile(src,dst); - } - - class Cubemap extends bg.scene.Component { - static Current(context) { - if (!g_currentCubemap) { - g_currentCubemap = bg.base.TextureCache.WhiteCubemap(context); - } - return g_currentCubemap; - } - - constructor() { - super(); - this._images = [null, null, null, null, null, null]; - this._texture = null; - } - - setImageUrl(imgCode,texture) { - this._images[imgCode] = texture; - } - - getImageUrl(imgCode) { - return this._images[imgCode]; - } - - get texture() { - return this._texture; - } - - loadCubemap(context) { - context = context || this.node && this.node.context; - return new Promise((resolve,reject) => { - bg.utils.Resource.LoadMultiple(this._images) - .then((result) => { - this._texture = new bg.base.Texture(context); - this._texture.target = bg.base.TextureTarget.CUBE_MAP; - this._texture.create(); - this._texture.bind(); - - this._texture.setCubemap( - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Z)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Z)] - ); - - g_currentCubemap = this._texture; - bg.emitImageLoadEvent(result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)]); - resolve(this); - }) - - .catch((err) => { - reject(err); - }); - }); - } - - clone() { - let cubemap = new Cubemap(); - for (let code in this._images) { - cubemap._images[code] = this._images[code]; - }; - cubemap._texture = this._texture; - return cubemap; - } - - deserialize(context,sceneData,url) { - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["positiveX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["negativeX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["positiveY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["negativeY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["positiveZ"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["negativeZ"]) - ); - return this.loadCubemap(context); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - if (!bg.isElectronApp) return; - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Z,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Z,url.path])); - } - } - - bg.scene.registerComponent(bg.scene,Cubemap,"bg.scene.Cubemap"); -})(); -(function() { - - function escapePathCharacters(name) { - if (!name) { - return bg.utils.generateUUID(); - } - else { - var illegalRe = /[\/\?<>\\:\*\|":\[\]\(\)\{\}]/g; - var controlRe = /[\x00-\x1f\x80-\x9f]/g; - var reservedRe = /^\.+$/; - var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; - var windowsTrailingRe = /[\. ]+$/; - - function sanitize(input, replacement) { - var sanitized = input - .replace(illegalRe, replacement) - .replace(controlRe, replacement) - .replace(reservedRe, replacement) - .replace(windowsReservedRe, replacement) - .replace(windowsTrailingRe, replacement); - return sanitized; - } - - return sanitize(name,'-'); - } - } - class Drawable extends bg.scene.Component { - - // It creates a copy of the node with all its components, except the drawable - // component, that will be an instance (share the same polyList instances) - static InstanceNode(node) { - let newNode = new bg.scene.Node(node.context,node.name ? `copy of ${node.name}`:""); - newNode.enabled = node.enabled; - node.forEachComponent((comp) => { - let newComp = null; - if (comp instanceof Drawable) { - newComp = comp.instance(); - } - else { - newComp = comp.clone(); - } - newNode.addComponent(newComp); - }); - return newNode; - } - - constructor(name="") { - super(); - - this._name = name; - this._items = []; // { polyList:p, material:m, transform:t } - } - - get name() { return this._name; } - set name(n) { this._name = n; } - - clone(newName) { - let newInstance = new bg.scene.Drawable(); - newInstance.name = newName || `copy of ${this.name}`; - this.forEach((plist,material,trx) => { - newInstance.addPolyList(plist.clone(), material.clone(), trx ? new bg.Matrix4(trx):null); - }); - return newInstance; - } - - destroy() { - this.forEach((plist) => { - plist.destroy(); - }); - this._name = ""; - this._items = []; - } - - // It works as clone(), but it doesn't duplicate the polyList - instance(newName) { - let newInstance = new bg.scene.Drawable(); - newInstance.name = newName || `copy of ${this.name}`; - this.forEach((plist,material,trx) => { - newInstance.addPolyList(plist, material.clone(), trx ? new bg.Matrix4(trx):null); - }); - return newInstance; - } - - addPolyList(plist,mat,trx=null) { - if (plist && this.indexOf(plist)==-1) { - mat = mat || new bg.base.Material(); - - this._items.push({ - polyList:plist, - material:mat, - transform:trx - }); - return true; - } - return false; - } - - getExternalResources(resources = []) { - this.forEach((plist,material) => { - material.getExternalResources(resources) - }); - return resources; - } - - // Apply a material definition object to the polyLists - applyMaterialDefinition(materialDefinitions,resourcesUrl) { - let promises = []; - this.forEach((plist,mat) => { - let definition = materialDefinitions[plist.name]; - if (definition) { - promises.push(new Promise((resolve,reject) => { - let modifier = new bg.base.MaterialModifier(definition); - mat.applyModifier(plist.context,modifier,resourcesUrl); - resolve(); - })); - } - }); - return Promise.all(promises); - } - - removePolyList(plist) { - let index = -1; - this._items.some((item, i) => { - if (plist==item.polyList) { - index = i; - } - }) - if (index>=0) { - this._items.splice(index,1); - } - } - - indexOf(plist) { - let index = -1; - this._items.some((item,i) => { - if (item.polyList==plist) { - index = i; - return true; - } - }); - return index; - } - - replacePolyList(index,plist) { - if (index>=0 && index=0 && index=0 && index=0 && index=0 && index=0 && index { - if ((!isShadowMap && plist.visible) || (isShadowMap && plist.visibleToShadows) || forceDraw) { - let currMaterial = pipeline.effect.material; - if (trx) { - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.mult(trx); - } - - if (pipeline.shouldDraw(mat)) { - pipeline.effect.material = mat; - pipeline.draw(plist); - } - - if (trx) { - matrixState.modelMatrixStack.pop(); - } - pipeline.effect.material = currMaterial; - } - }); - } - } - - //// Render queue method - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (!this.node.enabled) { - return; - } - - this.forEach((plist,mat,trx) => { - if (!plist.visible) { - return; - } - if (trx) { - modelMatrixStack.push(); - modelMatrixStack.mult(trx); - } - - if (mat.isTransparent) { - renderQueue.renderTransparent(plist,mat,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - else { - renderQueue.renderOpaque(plist,mat,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - - if (trx) { - modelMatrixStack.pop(trx); - } - }); - } - - setGroupVisible(groupName,visibility=true) { - this.forEach((plist) => { - if (plist.groupName==groupName) { - plist.visible = visibility; - } - }); - } - - hideGroup(groupName) { this.setGroupVisible(groupName,false); } - - showGroup(groupName) { this.setGroupVisible(groupName,true); } - - setVisibleByName(name,visibility=true) { - this.some((plist) => { - if (plist.name==name) { - plist.visible = visibility; - return true; - } - }); - } - - showByName(name) { - this.setVisibleByName(name,true); - } - - hideByName(name) { - this.setVisibleByName(name,false); - } - - deserialize(context,sceneData,url) { - return new Promise((resolve,reject) => { - let modelUrl = bg.utils.Resource.JoinUrl(url,sceneData.name + '.vwglb'); - bg.base.Loader.Load(context,modelUrl) - .then((node) => { - let drw = node.component("bg.scene.Drawable"); - this._name = sceneData.name; - this._items = drw._items; - resolve(this); - }); - }); - } - - serialize(componentData,promises,url) { - if (!bg.isElectronApp) { - return; - } - super.serialize(componentData,promises,url); - this.name = escapePathCharacters(this.name); - - componentData.name = this.name; - const path = require('path'); - let dst = path.join(url.path,componentData.name + ".vwglb"); - promises.push(new Promise((resolve,reject) => { - bg.base.Writer.Write(dst,this.node) - .then(() => resolve()) - .catch((err) => reject(err)); - })); - } - } - - bg.scene.registerComponent(bg.scene,Drawable,"bg.scene.Drawable"); - -})(); -(function() { - - let s_lightRegister = []; - - function registerLight(l) { - s_lightRegister.push(l); - } - - function unregisterLight(l) { - let i = s_lightRegister.indexOf(l); - if (i!=-1) { - s_lightRegister.splice(i,1); - } - } - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i { - this._light = new bg.base.Light(context); - this._light.deserialize(sceneData); - resolve(this); - }); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - this.light.serialize(componentData); - } - } - - bg.scene.registerComponent(bg.scene,Light,"bg.scene.Light"); -})(); -(function() { - function parseMTL_n(line) { - let res = /newmtl\s+(.*)/.exec(line); - if (res) { - this._jsonData[res[1]] = JSON.parse(JSON.stringify(s_matInit)); - this._currentMat = this._jsonData[res[1]]; - } - } - - function parseMTL_N(line) { - let res = /Ns\s+([\d\.]+)/.exec(line); - if (res) { // Specular - this._currentMat.shininess = Number(res[1]); - } - //else if ( (res=/Ni\s+([\d\.]+)/.exec(line)) ) { - //} - } - - function vectorFromRE(re) { - return [ - Number(re[1]), - Number(re[2]), - Number(re[3]), - re[4] ? Number(re[4]) : 1.0 - ] - } - - function parseMTL_K(line) { - let res = /Kd\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s*([\d\.]*)/.exec(line); - if (res) { - // Diffuse - let d = vectorFromRE(res); - this._currentMat.diffuseR = d[0]; - this._currentMat.diffuseG = d[1]; - this._currentMat.diffuseB = d[2]; - this._currentMat.diffuseA = d[3]; - } - else if ( (res = /Ks\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s*([\d\.]*)/.exec(line)) ) { - // Specular - let s = vectorFromRE(res); - this._currentMat.specularR = s[0]; - this._currentMat.specularG = s[1]; - this._currentMat.specularB = s[2]; - this._currentMat.specularA = s[3]; - } - } - - function parseMTL_m(line) { - let res = /map_Kd\s+(.*)/.exec(line); - if (res) { - let path = res[1]; - path = path.replace(/\\/g,'/'); - let slashIndex = path.lastIndexOf('/'); - if (slashIndex>=0) { - path = path.substring(slashIndex + 1); - } - this._currentMat.texture = path; - } - } - - let s_matInit = { - diffuseR: 1.0, - diffuseG:1.0, - diffuseB:1.0, - diffuseA:1.0, - - specularR:1.0, - specularG:1.0, - specularB:1.0, - specularA:1.0, - - shininess: 0, - lightEmission: 0, - - refractionAmount: 0, - reflectionAmount: 0, - - textureOffsetX: 0, - textureOffsetY: 0, - textureScaleX: 1, - textureScaleY: 1, - - lightmapOffsetX: 0, - lightmapOffsetY: 0, - lightmapScaleX: 1, - lightmapScaleY: 1, - - normalMapOffsetX: 0, - normalMapOffsetY: 0, - normalMapScaleX: 1, - normalMapScaleY: 1, - - alphaCutoff: 0.5, - castShadows: true, - receiveShadows: true, - - shininessMaskChannel: 0, - shininessMaskInvert: false, - lightEmissionMaskChannel: 0, - lightEmissionMaskInvert: false, - - reflectionMaskChannel: 0, - reflectionMaskInvert: false, - - cullFace: true, - - texture: "", - lightmap: "", - normalMap: "", - shininessMask: "", - lightEmissionMask: "", - reflectionMask: "" - }; - - class MTLParser { - constructor(mtlData) { - this._jsonData = {} - this._currentMat = JSON.parse(JSON.stringify(s_matInit)); - let lines = mtlData.split('\n'); - - lines.forEach((line) => { - // First optimization: parse the first character and string lenght - line = line.trim(); - if (line.length>1 && line[0]!='#') { - // Second optimization: parse by the first character - switch (line[0]) { - case 'n': - parseMTL_n.apply(this,[line]); - break; - case 'N': - parseMTL_N.apply(this,[line]); - break; - case 'm': - parseMTL_m.apply(this,[line]); - break; - case 'd': - break; - case 'T': - break; - case 'K': - parseMTL_K.apply(this,[line]); - break; - case 'i': - break; - case 'o': - break; - } - } - }); - } - - get jsonData() { return this._jsonData; } - } - - function parseM(line) { - // mtllib - let res = /mtllib\s+(.*)/.exec(line); - if (res) { - this._mtlLib = res[1]; - } - } - - function parseG(line) { - // g - let res = /g\s+(.*)/.exec(line); - if (res) { - this._currentPlist.name = res[1]; - } - } - - function parseU(line) { - // usemtl - let res = /usemtl\s+(.*)/.exec(line); - if (res) { - this._currentPlist._matName = res[1]; - if (this._currentPlist.name=="") { - this._currentPlist.name = res[1]; - } - } - } - - function parseS(line) { - // s - let res = /s\s+(.*)/.exec(line); - if (res) { - // TODO: Do something with smoothing groups - } - } - - function addPoint(pointData) { - this._currentPlist.vertex.push(pointData.vertex[0],pointData.vertex[1],pointData.vertex[2]); - if (pointData.normal) { - this._currentPlist.normal.push(pointData.normal[0],pointData.normal[1],pointData.normal[2]); - } - if (pointData.tex) { - this._currentPlist.texCoord0.push(pointData.tex[0],pointData.tex[1]); - } - this._currentPlist.index.push(this._currentPlist.index.length); - } - - function isValid(point) { - return point && point.vertex && point.tex && point.normal; - } - - function addPolygon(polygonData) { - let currentVertex = 0; - let sides = polygonData.length; - if (sides<3) return; - while (currentVertex { - let name = this.url.replace(/[\\\/]/ig,'-'); - let drawable = new bg.scene.Drawable(name); - let lines = data.split('\n'); - - let multiLine = ""; - lines.forEach((line) => { - line = line.trim(); - - // This section controls the break line character \ - // to concatenate this line with the next one - if (multiLine) { - line = multiLine + line; - } - if (line[line.length-1]=='\\') { - line = line.substring(0,line.length-1); - multiLine += line; - return; - } - else { - multiLine = ""; - } - - // First optimization: parse the first character and string lenght - if (line.length>1 && line[0]!='#') { - // Second optimization: parse by the first character - switch (line[0]) { - case 'v': - let res = /v\s+([\d\.\-e]+)\s+([\d\.\-e]+)\s+([\d\.\-e]+)/.exec(line); - if (res) { - this._vertexArray.push( - [ Number(res[1]), Number(res[2]), Number(res[3]) ] - ); - } - else if ( (res = /vn\s+([\d\.\-e]+)\s+([\d\.\-e]+)\s+([\d\.\-e]+)/.exec(line)) ) { - this._normalArray.push( - [ Number(res[1]), Number(res[2]), Number(res[3]) ] - ); - } - else if ( (res = /vt\s+([\d\.\-e]+)\s+([\d\.\-e]+)/.exec(line)) ) { - this._texCoordArray.push( - [ Number(res[1]), Number(res[2]) ] - ); - } - else { - console.warn("Error parsing line " + line); - } - break; - case 'm': - checkAddPlist.apply(this); - parseM.apply(this,[line]); - break; - case 'g': - checkAddPlist.apply(this); - parseG.apply(this,[line]); - break; - case 'u': - checkAddPlist.apply(this); - parseU.apply(this,[line]); - break; - case 's': - //checkAddPlist.apply(this); - parseS.apply(this,[line]); - break; - case 'f': - parseF.apply(this,[line]); - break; - case 'o': - checkAddPlist.apply(this); - parseO.apply(this,[line]); - break; - } - } - }); - - if (this._currentPlist && this._addPlist) { - this._currentPlist.build(); - this._plistArray.push(this._currentPlist); - } - - function buildDrawable(plistArray,materials) { - plistArray.forEach((plist) => { - let mat = new bg.base.Material(); - let matData = materials[plist._matName]; - if (matData) { - let url = this.url.substring(0,this.url.lastIndexOf('/') + 1); - bg.base.Material.GetMaterialWithJson(this.context,matData,url) - .then((material) => { - drawable.addPolyList(plist,material); - }) - } - else { - drawable.addPolyList(plist,mat); - } - }); - } - - if (this._mtlLib) { - let locationUrl = this.url.substring(0,this.url.lastIndexOf("/")); - if (locationUrl.length>0 && locationUrl!='/') locationUrl += "/"; - bg.utils.Resource.Load(locationUrl + this._mtlLib) - .then((data) => { - buildDrawable.apply(this,[this._plistArray,parseMTL(data)]); - resolve(drawable); - }) - .catch(() => { - bg.log("Warning: no such material library file for obj model " + this.url); - buildDrawable.apply(this,[this._plistArray,{}]); - resolve(drawable); - }); - } - else { - buildDrawable.apply(this,[this._plistArray,{}]); - resolve(drawable); - } - }); - } - } - - class OBJLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - return bg.utils.Resource.GetExtension(url)=="obj"; - } - - load(context,url,data) { - return new Promise((resolve,reject) => { - if (data) { - try { - let parser = new OBJParser(context,url); - let resultNode = null; - let basePath = url.split("/"); - basePath.pop(); - basePath = basePath.join("/") + '/'; - let matUrl = url.split("."); - matUrl.pop(); - matUrl.push("bg2mat"); - matUrl = matUrl.join("."); - parser.loadDrawable(data) - .then((drawable) => { - let node = new bg.scene.Node(context,drawable.name); - node.addComponent(drawable); - resultNode = node; - return bg.utils.Resource.LoadJson(matUrl); - }) - - .then((matData) => { - let promises = []; - try { - let drw = resultNode.component("bg.scene.Drawable"); - drw.forEach((plist,mat)=> { - let matDef = null; - matData.some((defItem) => { - if (defItem.name==plist.name) { - matDef = defItem; - return true; - } - }); - - if (matDef) { - let p = bg.base.Material.FromMaterialDefinition(context,matDef,basePath); - promises.push(p) - p.then((newMat) => { - mat.assign(newMat); - }); - } - }); - } - catch(err) { - - } - return Promise.all(promises); - }) - - .then(() => { - resolve(resultNode); - }) - - .catch(() => { - // bg2mat file not found - resolve(resultNode) - }) - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading drawable. Data is null.")); - } - }); - } - } - - bg.base.OBJLoaderPlugin = OBJLoaderPlugin; -})(); -(function() { - - function createCube(context,w,h,d) { - let plist = new bg.base.PolyList(context); - - let x = w/2; - let y = h/2; - let z = d/2; - - plist.vertex = [ - x,-y,-z, -x,-y,-z, -x, y,-z, x, y,-z, // back face - x,-y, z, x,-y,-z, x, y,-z, x, y, z, // right face - -x,-y, z, x,-y, z, x, y, z, -x, y, z, // front face - -x,-y,-z, -x,-y, z, -x, y, z, -x, y,-z, // left face - -x, y, z, x, y, z, x, y,-z, -x, y,-z, // top face - x,-y, z, -x,-y, z, -x,-y,-z, x,-y,-z // bottom face - ]; - - plist.normal = [ - 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, // back face - 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // right face - 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // front face - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // left face - 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // top face - 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0 // bottom face - ]; - - plist.texCoord0 = [ - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1, - 0,0, 1,0, 1,1, 0,1 - ]; - - plist.index = [ - 0, 1, 2, 2, 3, 0, - 4, 5, 6, 6, 7, 4, - 8, 9,10, 10,11, 8, - 12,13,14, 14,15,12, - 16,17,18, 18,19,16, - 20,21,22, 22,23,20 - ]; - - plist.texCoord1 = bg.tools.UVMap.atlas(plist.vertex,plist.index,0.03); - - plist.build(); - return plist; - } - - function createPlane(context,w,d,plane='y') { - let x = w / 2.0; - let y = d / 2.0; - - let plist = new bg.base.PolyList(context); - - switch (plane.toLowerCase()) { - case 'x': - plist.vertex =[ 0.000000,-x,-y, - 0.000000, x,-y, - 0.000000, x, y, - 0.000000, x, y, - 0.000000,-x, y, - 0.000000,-x,-y]; - - plist.normal = [1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000, - 1.000000,0.000000,0.000000]; - - plist.texCoord0 = [ 0.000000,0.000000, - 1.000000,0.000000, - 1.000000,1.000000, - 1.000000,1.000000, - 0.000000,1.000000, - 0.000000,0.000000]; - - - plist.index = [2,1,0,5,4,3]; - break; - case 'y': - plist.vertex =[ -x,0.000000,-y, - x,0.000000,-y, - x,0.000000, y, - x,0.000000, y, - -x,0.000000, y, - -x,0.000000,-y]; - - plist.normal = [0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000, - 0.000000,1.000000,0.000000]; - - plist.texCoord0 = [ 0.000000,0.000000, - 1.000000,0.000000, - 1.000000,1.000000, - 1.000000,1.000000, - 0.000000,1.000000, - 0.000000,0.000000]; - - - plist.index = [2,1,0,5,4,3]; - break; - case 'z': - plist.vertex =[-x, y,0.000000, - -x,-y,0.000000, - x,-y,0.000000, - x,-y,0.000000, - x, y,0.000000, - -x, y,0.000000]; - - plist.normal = [0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000, - 0.000000,0.000000,1.000000]; - - plist.texCoord0 = [ - 0.000000,1.000000, - 0.000000,0.000000, - 1.000000,0.000000, - 1.000000,0.000000, - 1.000000,1.000000, - 0.000000,1.000000]; - - plist.index = [0,1,2,3,4,5]; - break; - } - - - plist.texCoord1 = [ - 0.00,0.95, - 0.00,0.00, - 0.95,0.00, - 0.95,0.00, - 0.95,0.95, - 0.00,0.95 - ]; - - - - plist.build(); - return plist; - } - - function createSphere(context,radius,slices,stacks) { - let plist = new bg.base.PolyList(context); - - ++slices; - const R = 1/(stacks-1); - const S = 1/(slices-1); - let r, s; - - let vertex = []; - let normal = []; - let texCoord = []; - let index = []; - - for(r = 0; r < stacks; r++) for(s = 0; s < slices; s++) { - const y = bg.Math.sin( -bg.Math.PI_2 + bg.Math.PI * r * R ); - const x = bg.Math.cos(2*bg.Math.PI * s * S) * bg.Math.sin(bg.Math.PI * r * R); - const z = bg.Math.sin(2*bg.Math.PI * s * S) * bg.Math.sin(bg.Math.PI * r * R); - texCoord.push(s * S); texCoord.push(r * R); - normal.push(x,y,z); - vertex.push(x * radius, y * radius, z * radius); - } - - for(r = 0; r < stacks - 1; r++) for(s = 0; s < slices - 1; s++) { - let i1 = r * slices + s; - let i2 = r * slices + (s + 1); - let i3 = (r + 1) * slices + (s + 1); - let i4 = (r + 1) * slices + s; - index.push(i1); index.push(i4); index.push(i3); - index.push(i3); index.push(i2); index.push(i1); - } - - plist.vertex = vertex; - plist.normal = normal; - plist.texCoord0 = texCoord; - - plist.texCoord1 = bg.tools.UVMap.atlas(vertex,index,0.03); - plist.index = index; - - plist.build(); - - return plist; - } - - function createDrawable(plist,name) { - let drawable = new bg.scene.Drawable(name); - drawable.addPolyList(plist); - return drawable; - } - - class PrimitiveFactory { - static CubePolyList(context,w=1,h,d) { - h = h || w; - d = d || w; - return createCube(context,w,h,d); - } - - static PlanePolyList(context,w=1,d,plane='y') { - d = d || w; - return createPlane(context,w,d,plane); - } - - static SpherePolyList(context,r=1,slices=20,stacks) { - stacks = stacks || slices; - return createSphere(context,r,slices,stacks); - } - - static Cube(context,w=1,h,d) { - h = h || w; - d = d || w; - return createDrawable(createCube(context,w,h,d),"Cube"); - } - - static Plane(context,w=1,d,plane='y') { - d = d || w; - return createDrawable(createPlane(context,w,d,plane),"Plane"); - } - - static Sphere(context,r=1,slices=20,stacks) { - stacks = stacks || slices; - return createDrawable(createSphere(context,r,slices,stacks),"Sphere"); - } - } - - bg.scene.PrimitiveFactory = PrimitiveFactory; - -})(); -(function() { - function fooScene(context) { - let root = new bg.scene.Node(context, "Scene Root"); - - bg.base.Loader.Load(context,"../data/test-shape.vwglb") - .then((node) => { - root.addChild(node); - node.addComponent(new bg.scene.Transform(bg.Matrix4.Translation(-1.4,0.25,0).scale(0.5,0.5,0.5))); - }) - - .catch(function(err) { - alert(err.message); - }); - - let sphereNode = new bg.scene.Node(context,"Sphere"); - sphereNode.addComponent(new bg.scene.Transform(bg.Matrix4.Translation(-1.3,0.1,1.3))); - sphereNode.addComponent(bg.scene.PrimitiveFactory.Sphere(context,0.1)); - sphereNode.component("bg.scene.Drawable").getMaterial(0).diffuse.a = 0.8; - sphereNode.component("bg.scene.Drawable").getMaterial(0).reflectionAmount = 0.4; - root.addChild(sphereNode); - - let floorNode = new bg.scene.Node(context,"Floor"); - floorNode.addComponent(new bg.scene.Transform(bg.Matrix4.Translation(0,0,0))); - floorNode.addComponent(bg.scene.PrimitiveFactory.Plane(context,10,10)); - floorNode.component("bg.scene.Drawable").getMaterial(0).shininess = 50; - floorNode.component("bg.scene.Drawable").getMaterial(0).reflectionAmount = 0.3; - floorNode.component("bg.scene.Drawable").getMaterial(0).normalMapScale = new bg.Vector2(10,10); - floorNode.component("bg.scene.Drawable").getMaterial(0).textureScale = new bg.Vector2(10,10); - floorNode.component("bg.scene.Drawable").getMaterial(0).reflectionMaskInvert = true; - floorNode.component("bg.scene.Drawable").getMaterial(0).shininessMaskInvert = true; - root.addChild(floorNode); - - bg.base.Loader.Load(context,"../data/bricks_nm.png") - .then((tex) => { - floorNode.component("bg.scene.Drawable").getMaterial(0).normalMap = tex; - }); - - bg.base.Loader.Load(context,"../data/bricks.jpg") - .then((tex) => { - floorNode.component("bg.scene.Drawable").getMaterial(0).texture = tex; - }); - - bg.base.Loader.Load(context,"../data/bricks_shin.jpg") - .then((tex) => { - floorNode.component("bg.scene.Drawable").getMaterial(0).reflectionMask = tex; - floorNode.component("bg.scene.Drawable").getMaterial(0).shininessMask = tex; - }); - - let lightNode = new bg.scene.Node(context,"Light"); - lightNode.addComponent(new bg.scene.Light(new bg.base.Light(context))); - lightNode.addComponent(new bg.scene.Transform(bg.Matrix4.Identity() - .rotate(bg.Math.degreesToRadians(30),0,1,0) - .rotate(bg.Math.degreesToRadians(35),-1,0,0))); - root.addChild(lightNode); - - let camera = new bg.scene.Camera(); - camera.isMain = true; - let cameraNode = new bg.scene.Node("Camera"); - cameraNode.addComponent(camera); - cameraNode.addComponent(new bg.scene.Transform()); - cameraNode.addComponent(new bg.manipulation.OrbitCameraController()); - let camCtrl = cameraNode.component("bg.manipulation.OrbitCameraController"); - camCtrl.minPitch = -45; - root.addChild(cameraNode); - - return root; - } - - class SceneFileParser { - constructor(url,jsonData) { - this.url = url.substring(0,url.lastIndexOf('/')); - this.jsonData = jsonData; - } - - loadNode(context,jsonData,parent,promises) { - // jsonData: object, input. Json data for the node - // parent: scene node, input. The parent node to which we must to add the new scene node. - // promises: array, output. Add promises from component.deserialize() - let node = new bg.scene.Node(context,jsonData.name); - node.enabled = jsonData.enabled; - node.steady = jsonData.steady || false; - parent.addChild(node); - jsonData.components.forEach((compData) => { - promises.push(bg.scene.Component.Factory(context,compData,node,this.url)); - }); - jsonData.children.forEach((child) => { - this.loadNode(context,child,node,promises); - }); - } - - loadScene(context) { - let promises = []; - let sceneRoot = new bg.scene.Node(context,"scene-root"); - - this.jsonData.scene.forEach((nodeData) => { - this.loadNode(context,nodeData,sceneRoot,promises); - }); - - return new Promise((resolve,reject) => { - Promise.all(promises) - .then(() => { - let findVisitor = new bg.scene.FindComponentVisitor("bg.scene.Camera"); - sceneRoot.accept(findVisitor); - - let cameraNode = null; - let firstCamera = null; - findVisitor.result.some((cn) => { - if (!firstCamera) { - firstCamera = cn; - } - if (cn.camera.isMain) { - cameraNode = cn; - return true; - } - }); - cameraNode = cameraNode || firstCamera; - if (!cameraNode) { - cameraNode = new bg.scene.Node(context,"Camera"); - cameraNode.addComponent(new bg.scene.Camera()); - let trx = bg.Matrix4.Rotation(0.52,-1,0,0); - trx.translate(0,0,5); - cameraNode.addComponent(new bg.scene.Transform(trx)); - sceneRoot.addChild(cameraNode); - } - - // Ensure that cameraNode is the only camera marked as main - bg.scene.Camera.SetAsMainCamera(cameraNode,sceneRoot); - resolve({ sceneRoot:sceneRoot, cameraNode:cameraNode }); - }); - }); - } - - } - - class SceneLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - let ext = bg.utils.Resource.GetExtension(url); - return ext=="vitscnj"; - } - - load(context,url,data) { - return new Promise((resolve,reject) => { - if (data) { - try { - if (typeof(data)=="string") { - // Prevent a bug in the C++ API version 2.0, that inserts a comma after the last - // element of some arrays and objects - data = data.replace(/,[\s\r\n]*\]/g,']'); - data = data.replace(/,[\s\r\n]*\}/g,'}'); - data = JSON.parse(data); - } - let parser = new SceneFileParser(url,data); - parser.loadScene(context) - .then((result) => { - resolve(result); - }); - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading scene. Data is null")); - } - }); - } - } - - bg.base.SceneLoaderPlugin = SceneLoaderPlugin; - -})(); -(function() { - - function copyCubemapImage(componentData,cubemapImage,dstPath) { - let path = require("path"); - let src = bg.base.Writer.StandarizePath(this.getImageUrl(cubemapImage)); - let file = src.split('/').pop(); - let dst = bg.base.Writer.StandarizePath(path.join(dstPath,file)); - switch (cubemapImage) { - case bg.scene.CubemapImage.POSITIVE_X: - componentData.positiveX = file; - break; - case bg.scene.CubemapImage.NEGATIVE_X: - componentData.negativeX = file; - break; - case bg.scene.CubemapImage.POSITIVE_Y: - componentData.positiveY = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Y: - componentData.negativeY = file; - break; - case bg.scene.CubemapImage.POSITIVE_Z: - componentData.positiveZ = file; - break; - case bg.scene.CubemapImage.NEGATIVE_Z: - componentData.negativeZ = file; - break; - } - return bg.base.Writer.CopyFile(src,dst); - } - - let g_backFace = [ 0.5,-0.5,-0.5, -0.5,-0.5,-0.5, -0.5, 0.5,-0.5, 0.5, 0.5,-0.5 ]; - let g_rightFace = [ 0.5,-0.5, 0.5, 0.5,-0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5 ]; - let g_frontFace = [ -0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5 ]; - let g_leftFace = [ -0.5,-0.5,-0.5, -0.5,-0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5,-0.5 ]; - let g_topFace = [ -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,-0.5, -0.5, 0.5,-0.5 ]; - let g_bottomFace = [ 0.5,-0.5, 0.5, -0.5,-0.5, 0.5, -0.5,-0.5,-0.5, 0.5,-0.5,-0.5 ]; - - let g_backFaceNorm = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 ]; - let g_rightFaceNorm = [-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0 ]; - let g_frontFaceNorm = [ 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ]; - let g_leftFaceNorm = [ 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 ]; - let g_topFaceNorm = [ 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0 ]; - let g_bottomFaceNorm = [ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]; - - let uv0 = 0; - let uv1 = 1; - let g_backFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_rightFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_frontFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_leftFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_topFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - let g_bottomFaceUV = [ uv1,uv0, uv0,uv0, uv0,uv1, uv1,uv1 ]; - - let g_index = [ 2,1,0, 0,3,2 ]; - - class Skybox extends bg.scene.Component { - constructor() { - super(); - this._images = [null, null, null, null, null, null]; - this._textures = []; - this._plist = []; - this._material = null; - } - - clone(context) { - let result = new Skybox(); - result._images = [ - this._images[0], - this._images[1], - this._images[2], - this._images[3], - this._images[4], - this._images[5] - ]; - context = context || this.node && this.node.context; - if (context) { - result.loadSkybox(context); - } - return result; - } - - setImageUrl(imgCode,texture) { - this._images[imgCode] = texture; - } - - getImageUrl(imgCode) { - return this._images[imgCode]; - } - - getTexture(imgCode) { - return this._textures[imgCode]; - } - - loadSkybox(context = null,onProgress = null) { - context = context || this.node && this.node.context; - - let backPlist = new bg.base.PolyList(context); - let rightPlist = new bg.base.PolyList(context); - let frontPlist = new bg.base.PolyList(context); - let leftPlist = new bg.base.PolyList(context); - let topPlist = new bg.base.PolyList(context); - let bottomPlist = new bg.base.PolyList(context); - - backPlist.vertex = g_backFace; backPlist.normal = g_backFaceNorm; backPlist.texCoord0 = g_backFaceUV; backPlist.texCoord1 = g_backFaceUV; backPlist.index = g_index; - backPlist.build(); - - rightPlist.vertex = g_rightFace; rightPlist.normal = g_rightFaceNorm; rightPlist.texCoord0 = g_rightFaceUV; rightPlist.texCoord1 = g_rightFaceUV; rightPlist.index = g_index; - rightPlist.build(); - - frontPlist.vertex = g_frontFace; frontPlist.normal = g_frontFaceNorm; frontPlist.texCoord0 = g_frontFaceUV; frontPlist.texCoord1 = g_frontFaceUV; frontPlist.index = g_index; - frontPlist.build(); - - leftPlist.vertex = g_leftFace; leftPlist.normal = g_leftFaceNorm; leftPlist.texCoord0 = g_leftFaceUV; leftPlist.texCoord1 = g_leftFaceUV; leftPlist.index = g_index; - leftPlist.build(); - - topPlist.vertex = g_topFace; topPlist.normal = g_topFaceNorm; topPlist.texCoord0 = g_topFaceUV; topPlist.texCoord1 = g_topFaceUV; topPlist.index = g_index; - topPlist.build(); - - bottomPlist.vertex = g_bottomFace; bottomPlist.normal = g_bottomFaceNorm; bottomPlist.texCoord0 = g_bottomFaceUV; bottomPlist.texCoord1 = g_bottomFaceUV; bottomPlist.index = g_index; - bottomPlist.build(); - - this._plist = [leftPlist,rightPlist,topPlist,bottomPlist,frontPlist,backPlist]; - this._material = new bg.base.Material(); - this._material.receiveShadows = false; - this._material.castShadows = false; - this._material.unlit = true; - - - return new Promise((resolve,reject) => { - bg.base.Loader.Load(context,this._images,onProgress, { - wrapX:bg.base.TextureWrap.MIRRORED_REPEAT, - wrapY:bg.base.TextureWrap.MIRRORED_REPEAT - }) - .then((result) => { - this._textures = [ - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_X)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Y)], - result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_Z)], - result[this.getImageUrl(bg.scene.CubemapImage.NEGATIVE_Z)] - ]; - this._textures.forEach((tex) => { - tex.wrapX = bg.base.TextureWrap.CLAMP; - tex.wrapY = bg.base.TextureWrap.CLAMP; - }); - bg.emitImageLoadEvent(result[this.getImageUrl(bg.scene.CubemapImage.POSITIVE_X)]); - resolve(); - }) - .catch((err) => { - reject(err); - }); - }) - } - - display(pipeline,matrixState) { - // TODO: extract far clip plane from projection matrix and use it to scale the cube before draw it - if (!pipeline.effect) { - throw new Error("Could not draw skybox: invalid effect"); - } - if (!this.node.enabled) { - return; - } - else if (this._textures.length==6) { - let curMaterial = pipeline.effect.material; - pipeline.effect.material = this._material; - matrixState.viewMatrixStack.push(); - matrixState.modelMatrixStack.push(); - matrixState.viewMatrixStack.matrix.setPosition(0,0,0); - - let projectionMatrix = matrixState.projectionMatrixStack.matrix; - let m22 = -projectionMatrix.m22; - let m32 = -projectionMatrix.m32; - let far = (2.0*m32)/(2.0*m22-2.0); - - let offset = 1; - let scale = bg.Math.sin(bg.Math.PI_4) * far - offset; - matrixState.modelMatrixStack.scale(scale,scale,scale); - - if (pipeline.shouldDraw(this._material)) { - this._plist.forEach((pl,index) => { - this._material.texture = this._textures[index]; - pipeline.draw(pl); - }); - } - - matrixState.modelMatrixStack.pop(); - matrixState.viewMatrixStack.pop(); - pipeline.effect.material = curMaterial; - } - } - - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this._textures.length==6) { - viewMatrixStack.push(); - modelMatrixStack.push(); - - viewMatrixStack.matrix.setPosition(0,0,0); - - let projectionMatrix = projectionMatrixStack.matrix; - let m22 = -projectionMatrix.m22; - let m32 = -projectionMatrix.m32; - let far = (2.0*m32)/(2.0*m22-2.0); - - let offset = 1; - let scale = bg.Math.sin(bg.Math.PI_4) * far - offset; - modelMatrixStack.scale(scale,scale,scale); - - this._plist.forEach((pl,index) => { - this._material.texture = this._textures[index]; - renderQueue.renderOpaque(pl,this._material.clone(),modelMatrixStack.matrix,viewMatrixStack.matrix); - }) - - viewMatrixStack.pop(); - modelMatrixStack.pop(); - } - } - - removedFromNode() { - this._plist.forEach((pl) => { - pl.destroy(); - }); - } - - deserialize(context,sceneData,url) { - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["positiveX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_X, - bg.utils.Resource.JoinUrl(url,sceneData["negativeX"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["positiveY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Y, - bg.utils.Resource.JoinUrl(url,sceneData["negativeY"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.POSITIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["positiveZ"]) - ); - this.setImageUrl( - bg.scene.CubemapImage.NEGATIVE_Z, - bg.utils.Resource.JoinUrl(url,sceneData["negativeZ"]) - ); - return this.loadSkybox(context); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - if (!bg.isElectronApp) return; - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_X,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Y,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.POSITIVE_Z,url.path])); - promises.push(copyCubemapImage.apply(this,[componentData,bg.scene.CubemapImage.NEGATIVE_Z,url.path])); - } - } - - bg.scene.registerComponent(bg.scene,Skybox,"bg.scene.Skybox"); -})(); -(function() { - class TextRect extends bg.scene.Component { - constructor(rectSize = new bg.Vector2(1,1),textureSize = new bg.Vector2(1000,1000)) { - super(); - - this._rectSize = rectSize; - this._textureSize = textureSize; - - this._textProperties = new bg.base.TextProperties(); - this._doubleSided = true; - this._unlit = false; - this._text = "Hello, World!"; - - this._sprite = null; - this._material = null; - - this._sizeMatrix = bg.Matrix4.Scale(this._rectSize.x,this._rectSize.y,1); - - this._canvasTexture = null; - this._dirty = true; - } - - clone() { - let newInstance = new bg.scene.TextRect(); - newInstance._text = this._text; - newInstance._sprite = this._sprite && this._sprite.clone(); - newInstance._material = this._material && this._material.clone(); - - // TODO: Clone other properties - return newInstance; - } - - get textProperties() { return this._textProperties; } - get text() { return this._text; } - set text(t) { this._dirty = true; this._text = t; } - get doubleSided() { return this._doubleSided; } - set doubleSided(ds) { this._dirty = true; this._doubleSided = ds; } - get unlit() { return this._unlit; } - set unlit(ul) { this._dirty = true; this._unlit = ul; } - get rectSize() { return this._rectSize; } - set rectSize(s) { - this._sizeMatrix.identity().scale(s.x,s.y,1); - this._rectSize = s; - } - - // TODO: update texture size - get textureSize() { return this._textureSize; } - set textureSize(t) { - this._dirty = true; - this._canvasTexture.resize(t.x,t.y); - this._textureSize = t; - } - - get material() { return this._material; } - - init() { - if (!this._sprite && this.node && this.node.context) { - this._sprite = bg.scene.PrimitiveFactory.PlanePolyList(this.node.context,1,1,'z'); - this._material = new bg.base.Material(); - this._material.alphaCutoff = 0.9; - this._dirty = true; - } - if (!this._canvasTexture && this.node && this.node.context) { - this._canvasTexture = new bg.tools.CanvasTexture(this.node.context,this._textureSize.x,this._textureSize.y, - (ctx,w,h) => { - ctx.clearRect(0,0,w,h); - if (this._textProperties.background!="transparent") { - ctx.fillStyle = this._textProperties.background; - ctx.fillRect(0,0,w,h); - } - ctx.fillStyle = this._textProperties.color; - let textSize = this._textProperties.size; - let font = this._textProperties.font; - let padding = 0; - let italic = this._textProperties.italic ? "italic" : ""; - let bold = this._textProperties.bold ? "bold" : ""; - ctx.textAlign = this._textProperties.align; - ctx.font = `${ italic } ${ bold } ${ textSize }px ${ font }`; // TODO: Font and size - let textWidth = ctx.measureText(this._text); - let x = 0; - let y = 0; - switch (ctx.textAlign) { - case "center": - x = w / 2; - y = textSize + padding; - break; - case "right": - x = w; - y = textSize + padding; - break; - default: - x = padding; - y = textSize + padding; - } - let textLines = this._text.split("\n"); - textLines.forEach((line) => { - ctx.fillText(line,x, y); - y += textSize; - }); - } - ); - this._dirty = true; - } - } - - frame(delta) { - if ((this._dirty || this._textProperties.dirty) && this._material && this._canvasTexture) { - this._canvasTexture.update(); - this._material.texture = this._canvasTexture.texture; - this._material.unlit = this._unlit; - this._material.cullFace = !this._doubleSided; - this._dirty = false; - this.textProperties.dirty = false; - } - } - - ////// Direct rendering functions: will be deprecated soon - display(pipeline,matrixState) { - if (!pipeline.effect) { - throw new Error("Could not draw TextRect: invalid effect"); - } - if (!this.node.enabled) { - return; - } - else if (this._sprite && this._material) { - if (this._sprite.visible) { - let curMaterial = pipeline.effect.material; - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.mult(this._sizeMatrix); - - if (pipeline.shouldDraw(this._material)) { - pipeline.effect.material = this._material; - pipeline.draw(this._sprite); - } - - matrixState.modelMatrixStack.pop(); - pipeline.effect.material = curMaterial; - } - } - } - - ///// Render queue functions - draw(renderQueue,modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this._sprite && this._material) { - modelMatrixStack.push(); - modelMatrixStack.mult(this._sizeMatrix); - - if (this._material.isTransparent) { - renderQueue.renderTransparent(this._sprite,this._material,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - else { - renderQueue.renderOpaque(this._sprite,this._material,modelMatrixStack.matrix,viewMatrixStack.matrix); - } - - modelMatrixStack.pop(); - } - } - - serialize(componentData,promises,url) { - componentData.textProperties = {}; - this.textProperties.serialize(componentData.textProperties); - componentData.text = this.text; - componentData.doubleSided = this.doubleSided; - componentData.unlit = this.unlit; - componentData.textureSize = this.textureSize.toArray(); - componentData.rectSize = this.rectSize.toArray(); - } - - deserialize(context,sceneData,url) { - this.textProperties.deserialize(sceneData.textProperties); - this.text = sceneData.text; - this.doubleSided = sceneData.doubleSided; - this.unlit = sceneData.unlit; - this.textureSize = new bg.Vector2(sceneData.textureSize); - this.rectSize = new bg.Vector2(sceneData.rectSize); - } - } - - bg.scene.registerComponent(bg.scene,TextRect,"bg.scene.TextRect"); -})(); -(function() { - - class Transform extends bg.scene.Component { - constructor(matrix) { - super(); - - this._matrix = matrix || bg.Matrix4.Identity(); - this._globalMatrixValid = false; - this._transformVisitor = new bg.scene.TransformVisitor(); - } - - clone() { - let newTrx = new bg.scene.Transform(); - newTrx.matrix = new bg.Matrix4(this.matrix); - return newTrx; - } - - get matrix() { return this._matrix; } - set matrix(m) { this._matrix = m; } - - get globalMatrix() { - if (!this._globalMatrixValid) { - this._transformVisitor.clear(); - this.node.acceptReverse(this._transformVisitor); - this._globalMatrix = this._transformVisitor.matrix; - } - return this._globalMatrix; - } - - deserialize(context,sceneData,url) { - return new Promise((resolve,reject) => { - if (sceneData.transformStrategy) { - let str = sceneData.transformStrategy; - if (str.type=="TRSTransformStrategy") { - this._matrix - .identity() - .translate(str.translate[0],str.translate[1],str.translate[2]); - switch (str.rotationOrder) { - case "kOrderXYZ": - this._matrix - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateZ,0,0,1); - break; - case "kOrderXZY": - this._matrix - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateY,0,1,0); - break; - case "kOrderYXZ": - this._matrix - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateZ,0,0,1); - break; - case "kOrderYZX": - this._matrix - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateX,1,0,0); - break; - case "kOrderZYX": - this._matrix - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateY,0,1,0) - .rotate(str.rotateX,1,0,0); - break; - case "kOrderZXY": - this._matrix - .rotate(str.rotateZ,0,0,1) - .rotate(str.rotateX,1,0,0) - .rotate(str.rotateY,0,1,0); - break; - } - this._matrix.scale(str.scale[0],str.scale[1],str.scale[2]) - } - } - else if (sceneData.transformMatrix) { - this._matrix = new bg.Matrix4(sceneData.transformMatrix); - } - resolve(this); - }); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.transformMatrix = this._matrix.toArray(); - } - - // The direct render methods will be deprecated soon - ////// Direct render methods - willDisplay(pipeline,matrixState) { - if (this.node && this.node.enabled) { - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.mult(this.matrix); - } - } - - didDisplay(pipeline,matrixState) { - if (this.node && this.node.enabled) { - matrixState.modelMatrixStack.pop(); - } - this._globalMatrixValid = false; - } - ////// End direct render methods - - - ////// Render queue methods - willUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this.node && this.node.enabled) { - modelMatrixStack.push(); - modelMatrixStack.mult(this.matrix); - } - } - - didUpdate(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - if (this.node && this.node.enabled) { - modelMatrixStack.pop(); - } - this._globalMatrixValid = false; - } - ////// End render queue methods - - } - - bg.scene.registerComponent(bg.scene,Transform,"bg.scene.Transform"); - -})(); -(function() { - - class DrawVisitor extends bg.scene.NodeVisitor { - constructor(pipeline,matrixState) { - super(); - this._pipeline = pipeline || bg.base.Pipeline.Current(); - this._matrixState = matrixState || bg.base.MatrixState.Current(); - this._forceDraw = false; - } - - get forceDraw() { return this._forceDraw; } - set forceDraw(f) { this._forceDraw = f; } - - get pipeline() { return this._pipeline; } - get matrixState() { return this._matrixState; } - - visit(node) { - node.willDisplay(this.pipeline,this.matrixState); - node.display(this.pipeline,this.matrixState,this.forceDraw); - } - - didVisit(node) { - node.didDisplay(this.pipeline,this.matrixState); - } - } - - bg.scene.DrawVisitor = DrawVisitor; - - class RenderQueueVisitor extends bg.scene.NodeVisitor { - constructor(modelMatrixStack,viewMatrixStack,projectionMatrixStack) { - super(); - this._modelMatrixStack = modelMatrixStack || new bg.base.MatrixStack(); - this._viewMatrixStack = viewMatrixStack || new bg.base.MatrixStack(); - this._projectionMatrixStack = projectionMatrixStack || new bg.base.MatrixStack(); - this._renderQueue = new bg.base.RenderQueue(); - } - - get modelMatrixStack() { return this._modelMatrixStack; } - set modelMatrixStack(m) { this._modelMatrixStack = m; } - - get viewMatrixStack() { return this._viewMatrixStack; } - set viewMatrixStack(m) { this._viewMatrixStack = m; } - - get projectionMatrixStack() { return this._projectionMatrixStack } - set projectionMatrixStack(m) { this._projectionMatrixStack = m; } - - get renderQueue() { return this._renderQueue; } - - visit(node) { - node.willUpdate(this._modelMatrixStack); - node.draw(this._renderQueue,this._modelMatrixStack, this._viewMatrixStack, this._projectionMatrixStack); - } - - didVisit(node) { - node.didUpdate(this._modelMatrixStack, this._viewMatrixStack, this._projectionMatrixStack); - } - } - - bg.scene.RenderQueueVisitor = RenderQueueVisitor; - - class FrameVisitor extends bg.scene.NodeVisitor { - constructor() { - super(); - this._delta = 0; - } - - get delta() { return this._delta; } - set delta(d) { this._delta = d; } - - visit(node) { - node.frame(this.delta); - } - } - - bg.scene.FrameVisitor = FrameVisitor; - - class TransformVisitor extends bg.scene.NodeVisitor { - constructor() { - super(); - this._matrix = bg.Matrix4.Identity(); - } - - get matrix() { return this._matrix; } - - clear() { - this._matrix = bg.Matrix4.Identity(); - } - - visit(node) { - let trx = node.component("bg.scene.Transform"); - if (trx) { - this._matrix.mult(trx.matrix); - } - } - } - - bg.scene.TransformVisitor = TransformVisitor; - - class InputVisitor extends bg.scene.NodeVisitor { - - visit(node) { - if (this._operation) { - node[this._operation](this._event); - } - } - - keyDown(scene,evt) { - this._operation = "keyDown"; - this._event = evt; - scene.accept(this); - } - - keyUp(scene,evt) { - this._operation = "keyUp"; - this._event = evt; - scene.accept(this); - } - - mouseUp(scene,evt) { - this._operation = "mouseUp"; - this._event = evt; - scene.accept(this); - } - - mouseDown(scene,evt) { - this._operation = "mouseDown"; - this._event = evt; - scene.accept(this); - } - - mouseMove(scene,evt) { - this._operation = "mouseMove"; - this._event = evt; - scene.accept(this); - } - - mouseOut(scene,evt) { - this._operation = "mouseOut"; - this._event = evt; - scene.accept(this); - } - - mouseDrag(scene,evt) { - this._operation = "mouseDrag"; - this._event = evt; - scene.accept(this); - } - - mouseWheel(scene,evt) { - this._operation = "mouseWheel"; - this._event = evt; - scene.accept(this); - } - - touchStart(scene,evt) { - this._operation = "touchStart"; - this._event = evt; - scene.accept(this); - } - - touchMove(scene,evt) { - this._operation = "touchMove"; - this._event = evt; - scene.accept(this); - } - - touchEnd(scene,evt) { - this._operation = "touchEnd"; - this._event = evt; - scene.accept(this); - } - } - - bg.scene.InputVisitor = InputVisitor; - - class BoundingBoxVisitor extends bg.scene.NodeVisitor { - constructor() { - super(); - this.clear(); - } - - get min() { - return this._min; - } - - get max() { - return this._max; - } - - get size() { - return this._size; - } - - clear() { - // left, right, bottom, top, back, front - this._min = new bg.Vector3(bg.Math.FLOAT_MAX,bg.Math.FLOAT_MAX,bg.Math.FLOAT_MAX); - this._max = new bg.Vector3(-bg.Math.FLOAT_MAX,-bg.Math.FLOAT_MAX,-bg.Math.FLOAT_MAX); - this._size = new bg.Vector3(0,0,0); - } - - visit(node) { - let trx = bg.Matrix4.Identity(); - if (node.component("bg.scene.Transform")) { - trx = node.component("bg.scene.Transform").globalMatrix; - } - if (node.component("bg.scene.Drawable")) { - let bb = new bg.tools.BoundingBox(node.component("bg.scene.Drawable"),new bg.Matrix4(trx)); - this._min = bg.Vector.MinComponents(this._min,bb.min); - this._max = bg.Vector.MaxComponents(this._max,bb.max); - this._size = bg.Vector3.Sub(this._max, this._min); - } - } - } - - bg.scene.BoundingBoxVisitor = BoundingBoxVisitor; - - - class FindComponentVisitor extends bg.scene.NodeVisitor { - constructor(componentId) { - super(); - this.componentId = componentId; - this.clear(); - } - - get result() { - return this._result; - } - - clear() { - this._result = []; - } - - visit(node) { - if (node.component(this.componentId)) { - this._result.push(node); - } - } - } - - bg.scene.FindComponentVisitor = FindComponentVisitor; -})(); -(function() { - - function readBlock(arrayBuffer,offset) { - var block = new Uint8Array(arrayBuffer,offset,4); - block = String.fromCharCode(block[0]) + String.fromCharCode(block[1]) + String.fromCharCode(block[2]) + String.fromCharCode(block[3]); - return block; - } - - function readInt(arrayBuffer,offset) { - var dataView = new DataView(arrayBuffer,offset,4); - return dataView.getInt32(0); - } - - function readFloat(arrayBuffer,offset) { - var dataView = new DataView(arrayBuffer,offset,4); - return dataView.getFloat32(0); - } - - function readMatrix4(arrayBuffer,offset) { - var response = {offset:0,data:[]} - var size = 16; - var dataView = new DataView(arrayBuffer,offset, size*4); - var littleEndian = false; - for (var i=0;i=data.byteLength) { - done = true; - } - - let plistData = { - name:plistName, - matName:matName, - vertices:vArray, - normal:nArray, - texcoord0:t0Array, - texcoord1:t1Array, - texcoord2:t2Array, - indices:iArray - } - polyLists.push(plistData) - plistName = ""; - matName = ""; - vArray = null; - nArray = null; - t0Array = null; - t1Array = null; - t2Array = null; - iArray = null; - break; - default: - throw "File format exception. Unexpected poly list member found"; - } - } - - var parsedData = { - version:version, - polyList:polyLists, - materials: {} - } - this._componentData = components; - materials.forEach((matData) => { - parsedData.materials[matData.name] = matData; - }); - return parsedData; - } - - createDrawable(data,path) { - let drawable = new bg.scene.Drawable(this.context); - drawable._version = data.version; - let promises = []; - - data.polyList.forEach((plistData) => { - let materialData = data.materials[plistData.matName]; - - let polyList = new bg.base.PolyList(this._context); - polyList.name = plistData.name; - polyList.vertex = plistData.vertices || polyList.vertex; - polyList.normal = plistData.normal || polyList.normal; - polyList.texCoord0 = plistData.texcoord0 || polyList.texCoord0; - polyList.texCoord1 = plistData.texcoord1 || polyList.texCoord1; - polyList.texCoord2 = plistData.texcoord2 || polyList.texCoord2; - polyList.index = plistData.indices || polyList.index; - - polyList.groupName = materialData.groupName; - polyList.visible = materialData.visible; - polyList.visibleToShadows = materialData.visibleToShadows!==undefined ? materialData.visibleToShadows : true; - - polyList.build(); - - promises.push(bg.base.Material.GetMaterialWithJson(this._context,materialData,path) - .then(function(material) { - drawable.addPolyList(polyList,material); - })); - }); - - return Promise.all(promises) - .then(() => { - return drawable; - }); - } - - addComponents(node,url) { - if (this._jointData) { - let i = null; - let o = null; - if (this._jointData.input) { - i = this._jointData.input; - } - if (this._jointData.output && this._jointData.output.length) { - o = this._jointData.output[0]; - } - - if (i) addJoint(node,"InputChainJoint",i); - if (o) addJoint(node,"OutputChainJoint",o); - } - - if (this._componentData) { - console.log("Component data found"); - let baseUrl = url; - if (bg.isElectronApp) { - baseUrl = bg.base.Writer.StandarizePath(url); - } - baseUrl = baseUrl.split("/"); - baseUrl.pop(); - baseUrl = baseUrl.join("/"); - this._componentData.forEach((cmpData) => { - bg.scene.Component.Factory(this.context,cmpData,node,baseUrl) - }) - } - } - } - - class VWGLBLoaderPlugin extends bg.base.LoaderPlugin { - acceptType(url,data) { - let ext = bg.utils.Resource.GetExtension(url); - return ext=="vwglb" || ext=="bg2"; - } - - load(context,url,data) { - return new Promise((accept,reject) => { - if (data) { - try { - let parser = new VWGLBParser(context,data); - let path = url.substr(0,url.lastIndexOf("/")); - parser.loadDrawable(data,path) - .then((drawable) => { - let node = new bg.scene.Node(context,drawable.name); - node.addComponent(drawable); - parser.addComponents(node,url); - accept(node); - }); - } - catch(e) { - reject(e); - } - } - else { - reject(new Error("Error loading drawable. Data is null")); - } - }); - } - } - - // This plugin load vwglb and bg2 files, but will also try to load the associated bg2mat file - class Bg2LoaderPlugin extends VWGLBLoaderPlugin { - load(context,url,data) { - let promise = super.load(context,url,data); - return new Promise((resolve,reject) => { - promise - .then((node) => { - let basePath = url.split("/"); - basePath.pop(); - basePath = basePath.join("/") + '/'; - let matUrl = url.split("."); - matUrl.pop(); - matUrl.push("bg2mat"); - matUrl = matUrl.join("."); - bg.utils.Resource.LoadJson(matUrl) - .then((matData) => { - let promises = []; - try { - let drw = node.component("bg.scene.Drawable"); - drw.forEach((plist,mat)=> { - let matDef = null; - matData.some((defItem) => { - if (defItem.name==plist.name) { - matDef = defItem; - return true; - } - }); - - if (matDef) { - let p = bg.base.Material.FromMaterialDefinition(context,matDef,basePath); - promises.push(p) - p.then((newMat) => { - mat.assign(newMat); - }); - } - }); - } - catch(err) { - - } - return Promise.all(promises); - }) - .then(() => { - resolve(node); - }) - .catch(() => { // bg2mat file not found - resolve(node); - }); - }) - .catch((err) => { - reject(err); - }); - }); - } - } - - bg.base.VWGLBLoaderPlugin = VWGLBLoaderPlugin; - bg.base.Bg2LoaderPlugin = Bg2LoaderPlugin; - -})(); -bg.manipulation = {}; -(function() { - - class DrawGizmoVisitor extends bg.scene.DrawVisitor { - constructor(pipeline,matrixState) { - super(pipeline,matrixState); - this._sprite = bg.scene.PrimitiveFactory.PlanePolyList(pipeline.context,1,1,"z"); - - this._gizmoScale = 1; - - this._gizmoIcons = []; - - this._show3dGizmos = true; - } - - get gizmoScale() { return this._gizmoScale; } - set gizmoScale(s) { this._gizmoScale = s; } - - get show3dGizmos() { return this._show3dGizmos; } - set show3dGizmos(g) { this._show3dGizmos = g; } - - clearGizmoIcons() { this._gizmoIcons = []; } - addGizmoIcon(type,icon,visible=true) { this._gizmoIcons.push({ type:type, icon:icon, visible:visible }); } - setGizmoIconVisibility(type,visible) { - this._gizmoIcons.some((iconData) => { - if (iconData.type==type) { - iconData.visible = visible; - } - }) - } - - get gizmoIcons() { return this._gizmoIcons; } - - getGizmoIcon(node) { - let icon = null; - this._gizmoIcons.some((iconData) => { - if (node.component(iconData.type) && iconData.visible) { - icon = iconData.icon; - return true; - } - }); - return icon; - } - - visit(node) { - super.visit(node); - - let icon = this.getGizmoIcon(node); - let gizmoOpacity = this.pipeline.effect.gizmoOpacity; - let gizmoColor = this.pipeline.effect.color; - this.pipeline.effect.color = bg.Color.White(); - let dt = this.pipeline.depthTest; - this.pipeline.depthTest = false; - if (icon) { - this.pipeline.effect.texture = icon; - this.pipeline.effect.gizmoOpacity = 1; - this.matrixState.viewMatrixStack.push(); - this.matrixState.modelMatrixStack.push(); - this.matrixState.viewMatrixStack.mult(this.matrixState.modelMatrixStack.matrix); - this.matrixState.modelMatrixStack.identity(); - this.matrixState.viewMatrixStack.matrix.setRow(0,new bg.Vector4(1,0,0,0)); - this.matrixState.viewMatrixStack.matrix.setRow(1,new bg.Vector4(0,1,0,0)); - this.matrixState.viewMatrixStack.matrix.setRow(2,new bg.Vector4(0,0,1,0)); - let s = this.matrixState.cameraDistanceScale * 0.05 * this._gizmoScale; - this.matrixState.viewMatrixStack.scale(s,s,s); - this.pipeline.draw(this._sprite); - - this.matrixState.viewMatrixStack.pop(); - this.matrixState.modelMatrixStack.pop(); - this.pipeline.effect.gizmoOpacity = gizmoOpacity; - this.pipeline.effect.texture = null; - } - if (this._show3dGizmos) { - node.displayGizmo(this.pipeline,this.matrixState); - } - this.pipeline.effect.color = gizmoColor; - this.pipeline.depthTest = dt; - } - - } - - bg.manipulation = bg.manipulation || {}; - bg.manipulation.DrawGizmoVisitor = DrawGizmoVisitor; -})(); -(function() { - - class GizmoManager extends bg.app.ContextObject { - - constructor(context) { - super(context); - this._gizmoOpacity = 0.9; - } - - get pipeline() { - if (!this._pipeline) { - this._pipeline = new bg.base.Pipeline(this.context); - this._pipeline.blendMode = bg.base.BlendMode.NORMAL; - this._pipeline.effect = new bg.manipulation.GizmoEffect(this.context); - } - return this._pipeline; - } - - get matrixState() { - if (!this._matrixState) { - this._matrixState = new bg.base.MatrixState(); - } - return this._matrixState; - } - - get drawVisitor() { - if (!this._drawVisitor) { - this._drawVisitor = new bg.manipulation.DrawGizmoVisitor(this.pipeline,this.matrixState); - } - return this._drawVisitor; - } - - get gizmoOpacity() { return this._gizmoOpacity; } - set gizmoOpacity(o) { this._gizmoOpacity = o; } - - get show3dGizmos() { return this.drawVisitor.show3dGizmos; } - set show3dGizmos(g) { this.drawVisitor.show3dGizmos = g; } - - get working() { return this._working; } - - // Load icon textures manually - // addGizmoIcon("bg.scene.Camera",cameraTexture) - addGizmoIcon(type,iconTexture) { - this.drawVisitor.addGizmoIcon(type,iconTexture); - } - - get gizmoIconScale() { return this.drawVisitor.gizmoScale; } - set gizmoIconScale(s) { this.drawVisitor.gizmoScale = s; } - - setGizmoIconVisibility(type,visible) { this.drawVisitor.setGizmoIconVisibility(type,visible); } - hideGizmoIcon(type) { this.drawVisitor.setGizmoIconVisibility(type,false); } - showGizmoIcon(type) { this.drawVisitor.setGizmoIconVisibility(type,true); } - - get gizmoIcons() { return this.drawVisitor.gizmoIcons; } - - /* - * Receives an array with the icon data, ordered by priority (only one component - * icon will be shown). - * iconData: [ - * { type:"bg.scene.Camera", icon:"../data/camera_gizmo.png" }, - * { type:"bg.scene.Light", icon:"../data/light_gizmo.png" }, - * { type:"bg.scene.Transform", icon:"../data/transform_gizmo.png" }, - * { type:"bg.scene.Drawable", icon:"../data/drawable_gizmo.png" }, - * ], - * basePath: if specified, this path will be prepended to the icon paths - */ - loadGizmoIcons(iconData, basePath="",onProgress) { - return new Promise((resolve,reject) => { - let urls = []; - let iconDataResult = []; - iconData.forEach((data) => { - let itemData = { type:data.type, iconTexture:null }; - itemData.path = bg.utils.path.join(basePath,data.icon); - urls.push(itemData.path); - iconDataResult.push(itemData); - }); - bg.base.Loader.Load(this.context,urls,onProgress) - .then((result) => { - iconDataResult.forEach((dataItem) => { - dataItem.iconTexture = result[dataItem.path]; - this.addGizmoIcon(dataItem.type,dataItem.iconTexture); - }) - resolve(iconDataResult); - }) - .catch((err) => { - reject(err); - }); - }); - } - - clearGizmoIcons() { - this.drawVisitor.clearGizmoIcons(); - } - - startAction(gizmoPickData,pos) { - this._working = true; - this._startPoint = pos; - this._currentGizmoData = gizmoPickData; - if (this._currentGizmoData && this._currentGizmoData.node) { - let gizmo = this._currentGizmoData.node.component("bg.manipulation.Gizmo"); - if (gizmo) { - gizmo.beginDrag(this._currentGizmoData.action,pos); - } - } - } - - move(pos,camera) { - if (this._currentGizmoData && this._currentGizmoData.node) { - let gizmo = this._currentGizmoData.node.component("bg.manipulation.Gizmo"); - if (gizmo) { - pos.y = camera.viewport.height - pos.y; // Convert to viewport coords - gizmo.drag(this._currentGizmoData.action,this._startPoint,pos,camera); - } - this._startPoint = pos; - } - } - - endAction() { - if (this._currentGizmoData && this._currentGizmoData.node) { - let gizmo = this._currentGizmoData.node.component("bg.manipulation.Gizmo"); - if (gizmo) { - gizmo.endDrag(this._currentGizmoData.action); - } - } - this._working = false; - this._startPoint = null; - this._currentGizmoData = null; - } - - drawGizmos(sceneRoot,camera,clearDepth=true) { - let restorePipeline = bg.base.Pipeline.Current(); - let restoreMatrixState = bg.base.MatrixState.Current(); - bg.base.Pipeline.SetCurrent(this.pipeline); - bg.base.MatrixState.SetCurrent(this.matrixState); - this.pipeline.viewport = camera.viewport; - this.pipeline.effect.matrixState = this.matrixState; - - if (clearDepth) { - this.pipeline.clearBuffers(bg.base.ClearBuffers.DEPTH); - } - - this.matrixState.projectionMatrixStack.set(camera.projection); - this.matrixState.viewMatrixStack.set(camera.viewMatrix); - - let opacityLayer = this.pipeline.opacityLayer; - this.pipeline.opacityLayer = bg.base.OpacityLayer.NONE; - - this.pipeline.blend = true; - this.pipeline.effect.gizmoOpacity = this.gizmoOpacity; - sceneRoot.accept(this.drawVisitor); - this.pipeline.blend = false; - - this.pipeline.opacityLayer = opacityLayer; - - if (restorePipeline) { - bg.base.Pipeline.SetCurrent(restorePipeline); - } - if (restoreMatrixState) { - bg.base.MatrixState.SetCurrent(restoreMatrixState); - } - } - } - - bg.manipulation.GizmoManager = GizmoManager; - -})(); - -(function() { - - let shaders = {}; - - function initShaders() { - shaders[bg.webgl1.EngineId] = { - vertex: ` - attribute vec3 inVertex; - attribute vec2 inTexCoord; - attribute vec4 inVertexColor; - - uniform mat4 inModelMatrix; - uniform mat4 inViewMatrix; - uniform mat4 inProjectionMatrix; - - varying vec2 fsTexCoord; - varying vec4 fsColor; - - void main() { - fsTexCoord = inTexCoord; - fsColor = inVertexColor; - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - } - `, - - fragment:` - precision highp float; - - uniform vec4 inColor; - uniform sampler2D inTexture; - uniform float inOpacity; - - varying vec2 fsTexCoord; - varying vec4 fsColor; - - void main() { - vec4 tex = texture2D(inTexture,fsTexCoord); - gl_FragColor = vec4(fsColor.rgb * tex.rgb * inColor.rgb,inOpacity * tex.a); - } - ` - }; - } - - class GizmoEffect extends bg.base.Effect { - constructor(context) { - super(context); - initShaders(); - this._gizmoOpacity = 1; - this._color = bg.Color.White(); - } - - get inputVars() { - return { - vertex:'inVertex', - color:'inVertexColor', - tex0:'inTexCoord' - } - } - - set matrixState(m) { this._matrixState = m; } - get matrixState() { - return this._matrixState; - } - - set texture(t) { this._texture = t; } - get texture() { return this._texture; } - - set color(c) { this._color = c; } - get color() { return this._color; } - - set gizmoOpacity(o) { this._gizmoOpacity = o; } - get gizmoOpacity() { return this._gizmoOpacity; } - - get shader() { - if (!this._shader) { - this._shader = new bg.base.Shader(this.context); - this._shader.addShaderSource(bg.base.ShaderType.VERTEX, shaders[bg.webgl1.EngineId].vertex); - this._shader.addShaderSource(bg.base.ShaderType.FRAGMENT, shaders[bg.webgl1.EngineId].fragment); - this._shader.link(); - if (!this._shader.status) { - console.log(this._shader.compileError); - console.log(this._shader.linkError); - } - else { - this._shader.initVars([ - 'inVertex', - 'inVertexColor', - 'inTexCoord' - ],[ - 'inModelMatrix', - 'inViewMatrix', - 'inProjectionMatrix', - 'inColor', - 'inTexture', - 'inOpacity' - ]); - } - } - return this._shader - } - - setupVars() { - let whiteTexture = bg.base.TextureCache.WhiteTexture(this.context); - this.shader.setMatrix4('inModelMatrix',this.matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',new bg.Matrix4(this.matrixState.viewMatrixStack.matrixConst)); - this.shader.setMatrix4('inProjectionMatrix',this.matrixState.projectionMatrixStack.matrixConst); - this.shader.setVector4('inColor',this.color); - this.shader.setTexture('inTexture', this.texture ? this.texture : whiteTexture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setValueFloat('inOpacity',this.gizmoOpacity); - } - - } - - bg.manipulation.GizmoEffect = GizmoEffect; - - bg.manipulation.GizmoAction = { - TRANSLATE: 1, - ROTATE: 2, - ROTATE_FINE: 3, - SCALE: 4, - TRANSLATE_X: 5, - TRANSLATE_Y: 6, - TRANSLATE_Z: 7, - ROTATE_X: 8, - ROTATE_Y: 9, - ROTATE_Z: 10, - SCALE_X: 11, - SCALE_Y: 12, - SCALE_Z: 13, - - NONE: 99 - }; - - function getAction(plist) { - if (/rotate.*fine/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_FINE; - } - if (/rotate.*x/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_X; - } - if (/rotate.*y/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_Y; - } - if (/rotate.*z/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE_Z; - } - else if (/rotate/i.test(plist.name)) { - return bg.manipulation.GizmoAction.ROTATE; - } - else if (/translate.*x/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE_X; - } - else if (/translate.*y/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE_Y; - } - else if (/translate.*z/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE_Z; - } - else if (/translate/i.test(plist.name)) { - return bg.manipulation.GizmoAction.TRANSLATE; - } - else if (/scale.*x/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE_X; - } - else if (/scale.*y/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE_Y; - } - else if (/scale.*z/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE_Z; - } - else if (/scale/i.test(plist.name)) { - return bg.manipulation.GizmoAction.SCALE; - } - } - - let s_gizmoCache = {} - - class GizmoCache { - static Get(context) { - if (!s_gizmoCache[context.uuid]) { - s_gizmoCache[context.uuid] = new GizmoCache(context); - } - return s_gizmoCache[context.uuid]; - } - - constructor(context) { - this._context = context; - this._gizmos = {}; - } - - find(url) { - return this._gizmos[url]; - } - - register(url,gizmoItems) { - this._gizmos[url] = gizmoItems; - } - - unregister(url) { - if (this._gizmos[url]) { - delete this._gizmos[url]; - } - } - - clear() { - this._gizmos = {} - } - } - - bg.manipulation.GizmoCache = GizmoCache; - - function loadGizmo(context,gizmoUrl,gizmoNode) { - return new Promise(function(accept,reject) { - if (!gizmoUrl) { - accept([]); - return; - } - bg.base.Loader.Load(context,gizmoUrl) - .then(function (node) { - let drw = node.component("bg.scene.Drawable"); - let gizmoItems = []; - if (drw) { - drw.forEach(function (plist,material) { - gizmoItems.push({ - id:bg.manipulation.Selectable.GetIdentifier(), - type:bg.manipulation.SelectableType.GIZMO, - plist:plist, - material:material, - action:getAction(plist), - node:gizmoNode - }) - }); - } - - accept(gizmoItems); - }) - - .catch(function(err) { - reject(err); - }); - }); - } - - function rotationBetweenPoints(axis,p1,p2,origin,inc) { - if (!inc) inc = 0; - let v1 = new bg.Vector3(p2); - v1.sub(origin).normalize(); - let v2 = new bg.Vector3(p1); - v2.sub(origin).normalize(); - let dot = v1.dot(v2); - - let alpha = Math.acos(dot); - if (alpha>=inc || inc==0) { - if (inc!=0) { - alpha = (alpha>=2*inc) ? 2*inc:inc; - } - let sign = axis.dot(v1.cross(v2)); - if (sign<0) alpha *= -1.0; - let q = new bg.Quaternion(alpha,axis.x,axis.y,axis.z); - q.normalize(); - - if (!isNaN(q.x)) { - return q; - } - } - return new bg.Quaternion(0,0,1,0); - } - - class Gizmo extends bg.scene.Component { - constructor(gizmoPath,visible=true) { - super(); - this._gizmoPath = gizmoPath; - this._offset = new bg.Vector3(0); - this._visible = visible; - this._gizmoTransform = bg.Matrix4.Identity(); - this._gizmoP = bg.Matrix4.Identity(); - this._scale = 5; - this._minSize = 0.5; - } - - clone() { - let newGizmo = new Gizmo(this._gizmoPath); - newGizmo.offset.assign(this._offset); - newGizmo.visible = this._visible; - return newGizmo; - } - - get offset() { return this._offset; } - set offset(v) { this._offset = v; } - - get visible() { return this._visible; } - set visible(v) { this._visible = v; } - - get gizmoTransform() { - return this._gizmoTransform; - } - - beginDrag(action,pos) {} - - drag(action,startPos,endPos,camera) {} - - endDrag(action) {} - - findId(id) { - let result = null; - if (this._gizmoItems) { - this._gizmoItems.some((item) => { - if (item.id.r==id.r && item.id.g==id.g && item.id.b==id.b && item.id.a==id.a) { - result = item; - return true; - } - }); - } - return result; - } - - init() { - if (!this._error) { - this._gizmoItems = []; - loadGizmo(this.node.context,this._gizmoPath,this.node) - .then((gizmoItems) => { - this._gizmoItems = gizmoItems; - }) - - .catch((err) => { - this._error = true; - throw err; - }) - } - } - - frame(delta) { - - } - - display(pipeline,matrixState) { - if (!this._gizmoItems || !this.visible) return; - matrixState.modelMatrixStack.push(); - let modelview = new bg.Matrix4(matrixState.viewMatrixStack.matrix); - modelview.mult(matrixState.modelMatrixStack.matrix); - let s = modelview.position.magnitude() / this._scale; - matrixState.modelMatrixStack.matrix.setScale(s,s,s); - if (pipeline.effect instanceof bg.manipulation.ColorPickEffect && - (pipeline.opacityLayer & bg.base.OpacityLayer.GIZMOS || - pipeline.opacityLayer & bg.base.OpacityLayer.GIZMOS_SELECTION)) - { - let dt = pipeline.depthTest; - if (pipeline.opacityLayer & bg.base.OpacityLayer.GIZMOS_SELECTION) { // drawing gizmos in selection mode - pipeline.depthTest = true; - } - else { - pipeline.depthTest = false; - } - this._gizmoItems.forEach((item) => { - // The RGBA values are inverted because the alpha channel must be major than zero to - // produce any output in the framebuffer - if (item.plist.visible) { - pipeline.effect.pickId = new bg.Color(item.id.a/255,item.id.b/255,item.id.g/255,item.id.r/255); - pipeline.draw(item.plist); - } - }); - pipeline.depthTest = dt; - } - else if (pipeline.effect instanceof bg.manipulation.GizmoEffect) { - // Draw gizmo - this._gizmoItems.forEach((item) => { - if (item.plist.visible) { - pipeline.effect.texture = item.material.texture; - pipeline.effect.color = item.material.diffuse; - pipeline.draw(item.plist); - } - }) - } - matrixState.modelMatrixStack.pop(); - } - } - - function translateMatrix(gizmo,intersection) { - let matrix = new bg.Matrix4(gizmo.transform.matrix); - let rotation = matrix.rotation; - let origin = matrix.position; - - if (!gizmo._lastPickPoint) { - gizmo._lastPickPoint = intersection.ray.end; - gizmo._translateOffset = new bg.Vector3(origin); - gizmo._translateOffset.sub(intersection.ray.end); - } - - switch (Math.abs(gizmo.plane)) { - case bg.Axis.X: - matrix = bg.Matrix4.Translation(origin.x, - intersection.point.y + gizmo._translateOffset.y, - intersection.point.z + gizmo._translateOffset.z); - break; - case bg.Axis.Y: - matrix = bg.Matrix4.Translation(intersection.point.x + gizmo._translateOffset.x, - origin.y, - intersection.point.z + gizmo._translateOffset.z); - break; - case bg.Axis.Z: - matrix = bg.Matrix4.Translation(intersection.point.x + gizmo._translateOffset.x, - intersection.point.y + gizmo._translateOffset.y, - origin.z); - break; - } - - matrix.mult(rotation); - gizmo._lastPickPoint = intersection.point; - - return matrix; - } - - function rotateMatrix(gizmo,intersection,fine) { - let matrix = new bg.Matrix4(gizmo.transform.matrix); - let rotation = matrix.rotation; - let origin = matrix.position; - - if (!gizmo._lastPickPoint) { - gizmo._lastPickPoint = intersection.ray.end; - gizmo._translateOffset = new bg.Vector3(origin); - gizmo._translateOffset.sub(intersection.ray.end); - } - - if (!fine) { - let prevRotation = new bg.Matrix4(rotation); - rotation = rotationBetweenPoints(gizmo.planeAxis,gizmo._lastPickPoint,intersection.point,origin,bg.Math.degreesToRadians(22.5)); - if (rotation.x!=0 || rotation.y!=0 || rotation.z!=0 || rotation.w!=1) { - matrix = bg.Matrix4.Translation(origin) - .mult(rotation.getMatrix4()) - .mult(prevRotation); - gizmo._lastPickPoint = intersection.point; - } - } - else { - let prevRotation = new bg.Matrix4(rotation); - rotation = rotationBetweenPoints(gizmo.planeAxis,gizmo._lastPickPoint,intersection.point,origin); - if (rotation.x!=0 || rotation.y!=0 || rotation.z!=0 || rotation.w!=1) { - matrix = bg.Matrix4.Translation(origin) - .mult(rotation.getMatrix4()) - .mult(prevRotation); - gizmo._lastPickPoint = intersection.point; - } - } - - return matrix; - } - - function calculateClosestPlane(gizmo,matrixState) { - let cameraForward = matrixState.viewMatrixStack.matrix.forwardVector; - let upVector = matrixState.viewMatrixStack.matrix.upVector; - let xVector = new bg.Vector3(1,0,0); - let yVector = new bg.Vector3(0,1,0); - let zVector = new bg.Vector3(0,0,1); - let xVectorInv = new bg.Vector3(-1,0,0); - let yVectorInv = new bg.Vector3(0,-1,0); - let zVectorInv = new bg.Vector3(0,0,-1); - - let upAlpha = Math.acos(upVector.dot(yVector)); - if (upAlpha>0.9) { - gizmo.plane = bg.Axis.Y; - } - else { - let angles = [ - Math.acos(cameraForward.dot(xVector)), // x - Math.acos(cameraForward.dot(yVector)), // y - Math.acos(cameraForward.dot(zVector)), // z - Math.acos(cameraForward.dot(xVectorInv)), // -x - Math.acos(cameraForward.dot(yVectorInv)), // -y - Math.acos(cameraForward.dot(zVectorInv)) // -z - ]; - let min = angles[0]; - let planeIndex = 0; - angles.reduce(function(prev,v,index) { - if (v { - // The RGBA values are inverted because the alpha channel must be major than zero to - // produce any output in the framebuffer - if (item.plist.visible) { - pipeline.effect.pickId = new bg.Color(item.id.a/255,item.id.b/255,item.id.g/255,item.id.r/255); - pipeline.draw(item.plist); - } - }); - pipeline.depthTest = dt; - } - else if (pipeline.effect instanceof bg.manipulation.GizmoEffect) { - // Draw gizmo - this._gizmoItems.forEach((item) => { - if (item.plist.visible) { - pipeline.effect.texture = item.material.texture; - pipeline.effect.color = item.material.diffuse; - pipeline.draw(item.plist); - } - }) - } - matrixState.modelMatrixStack.pop(); - } - - beginDrag(action,pos) { - this._lastPickPoint = null; - } - - drag(action,startPos,endPos,camera) { - if (this.transform) { - let plane = new bg.physics.Plane(this.planeAxis); - let ray = bg.physics.Ray.RayWithScreenPoint(endPos,camera.projection,camera.viewMatrix,camera.viewport); - let intersection = bg.physics.Intersection.RayToPlane(ray,plane); - - if (intersection.intersects()) { - let matrix = new bg.Matrix4(this.transform.matrix); - this._gizmoP = bg.Matrix4.Translation(this.transform.matrix.position); - - switch (action) { - case bg.manipulation.GizmoAction.TRANSLATE: - matrix = translateMatrix(this,intersection); - break; - case bg.manipulation.GizmoAction.ROTATE: - matrix = rotateMatrix(this,intersection,false); - break; - case bg.manipulation.GizmoAction.ROTATE_FINE: - matrix = rotateMatrix(this,intersection,true); - break; - } - - this.transform.matrix = matrix; - } - } - } - - endDrag(action) { - this._lastPickPoint = null; - } - } - - class UnifiedGizmo extends Gizmo { - constructor(path,visible=true) { - super(path,visible); - this._translateSpeed = 0.005; - this._rotateSpeed = 0.005; - this._scaleSpeed = 0.001; - this._gizmoTransform = bg.Matrix4.Identity(); - } - - get gizmoTransform() { - return this._gizmoTransform; - } - - get translateSpeed() { return this._translateSpeed; } - set translateSpeed(s) { this._translateSpeed = s; } - - get rotateSpeed() { return this._rotateSpeed; } - set rotateSpeed(s) { this._rotateSpeed = s; } - - get scaleSpeed() { return this._scaleSpeed; } - set scaleSpeed(s) { this._scaleSpeed = s; } - - clone() { - let newGizmo = new PlaneGizmo(this._gizmoPath); - newGizmo.offset.assign(this._offset); - newGizmo.visible = this._visible; - return newGizmo; - } - - init() { - super.init(); - this._gizmoP = bg.Matrix4.Translation(this.transform.matrix.position); - this._gizmoTransform = this.transform.matrix.rotation; - } - - display(pipeline,matrixState) { - if (!this._gizmoItems || !this.visible) return; - super.display(pipeline,matrixState); - } - - beginDrag(action,pos) { - this._lastPickPoint = null; - } - - drag(action,startPos,endPos,camera) { - if (this.transform) { - if (!this._lastPickPoint) { - this._lastPickPoint = endPos; - } - - let matrix = new bg.Matrix4(this.transform.matrix); - this._gizmoP = bg.Matrix4.Translation(this.transform.matrix.position); - let diff = new bg.Vector2(this._lastPickPoint); - diff.sub(endPos); - - let matrixState = bg.base.MatrixState.Current(); - let modelview = new bg.Matrix4(matrixState.viewMatrixStack.matrix); - modelview.mult(matrixState.modelMatrixStack.matrix); - let s = modelview.position.magnitude() / this._scale; - s = s { - this._gizmoItems = gizmoItems; - bg.emitImageLoadEvent(); - }) - - .catch((err) => { - this._error = true; - throw err; - }) - } - } - } - - // All gizmo types share the same typeId, because a node can only contain one gizmo - bg.scene.registerComponent(bg.manipulation,Gizmo,"bg.manipulation.Gizmo"); - bg.scene.registerComponent(bg.manipulation,PlaneGizmo,"bg.manipulation.Gizmo"); - bg.scene.registerComponent(bg.manipulation,UnifiedGizmo,"bg.manipulation.Gizmo"); - bg.scene.registerComponent(bg.manipulation,MultiModeGizmo,"bg.manipulation.Gizmo"); - -})(); -(function() { - - let shader = {}; - - function initShaders() { - shader[bg.webgl1.EngineId] = { - vertex: ` - attribute vec3 inVertex; - - uniform mat4 inModelMatrix; - uniform mat4 inViewMatrix; - uniform mat4 inProjectionMatrix; - - void main() { - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - } - `, - - fragment:` - precision highp float; - - uniform vec4 inColorId; - - void main() { - gl_FragColor = inColorId; - } - ` - }; - } - - class ColorPickEffect extends bg.base.Effect { - constructor(context) { - super(context); - initShaders(); - } - - get inputVars() { - return { - vertex:'inVertex' - } - } - - set matrixState(m) { this._matrixState = m; } - get matrixState() { - return this._matrixState; - } - - set pickId(p) { this._pickId = p; } - get pickId() { return this._pickId || bg.Color.Transparent(); } - - get shader() { - if (!this._shader) { - this._shader = new bg.base.Shader(this.context); - this._shader.addShaderSource(bg.base.ShaderType.VERTEX, shader[bg.webgl1.EngineId].vertex); - this._shader.addShaderSource(bg.base.ShaderType.FRAGMENT, shader[bg.webgl1.EngineId].fragment); - this._shader.link(); - if (!this._shader.status) { - console.log(this._shader.compileError); - console.log(this._shader.linkError); - } - else { - this._shader.initVars([ - 'inVertex' - ],[ - 'inModelMatrix', - 'inViewMatrix', - 'inProjectionMatrix', - 'inColorId' - ]); - } - } - return this._shader - } - - setupVars() { - this.shader.setMatrix4('inModelMatrix',this.matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',new bg.Matrix4(this.matrixState.viewMatrixStack.matrixConst)); - this.shader.setMatrix4('inProjectionMatrix',this.matrixState.projectionMatrixStack.matrixConst); - this.shader.setVector4('inColorId', this.pickId); - } - - } - - bg.manipulation.ColorPickEffect = ColorPickEffect; - - class FindPickIdVisitor extends bg.scene.NodeVisitor { - constructor(target) { - super() - this._target = target; - } - - get target() { return this._target; } - set target(t) { this._target = t; this._result = null; } - - get result() { return this._result; } - - visit(node) { - let selectable = node.component("bg.manipulation.Selectable"); - let gizmo = node.component("bg.manipulation.Gizmo"); - if (gizmo && !gizmo.visible) { - gizmo = null; - } - this._result = this._result || - (selectable && selectable.findId(this.target)) || - (gizmo && gizmo.findId(this.target)); - } - } - - bg.manipulation.FindPickIdVisitor = FindPickIdVisitor; - - class MousePicker extends bg.app.ContextObject { - - constructor(context) { - super(context); - } - - get pipeline() { - if (!this._pipeline) { - this._pipeline = new bg.base.Pipeline(this.context); - - this._pipeline.effect = new ColorPickEffect(this.context); - this._renderSurface = new bg.base.TextureSurface(this.context); - this._renderSurface.create(); - this._pipeline.renderSurface = this._renderSurface; - this._pipeline.clearColor = new bg.Color(0,0,0,0); - } - return this._pipeline; - } - - get matrixState() { - if (!this._matrixState) { - this._matrixState = new bg.base.MatrixState(); - } - return this._matrixState; - } - - get drawVisitor() { - if (!this._drawVisitor) { - this._drawVisitor = new bg.scene.DrawVisitor(this.pipeline,this.matrixState); - } - return this._drawVisitor; - } - - pick(sceneRoot,camera,mousePosition) { - let restorePipeline = bg.base.Pipeline.Current(); - let restoreMatrixState = bg.base.MatrixState.Current(); - bg.base.Pipeline.SetCurrent(this.pipeline); - bg.base.MatrixState.SetCurrent(this.matrixState); - this.pipeline.viewport = camera.viewport; - this.pipeline.effect.matrixState = this.matrixState; - - - this.pipeline.clearBuffers(bg.base.ClearBuffers.COLOR | bg.base.ClearBuffers.DEPTH); - - this.matrixState.projectionMatrixStack.set(camera.projection); - this.matrixState.viewMatrixStack.set(camera.viewMatrix); - - let opacityLayer = this.pipeline.opacityLayer; - this.pipeline.opacityLayer = bg.base.OpacityLayer.SELECTION; - sceneRoot.accept(this.drawVisitor); - this.pipeline.opacityLayer = bg.base.OpacityLayer.GIZMOS_SELECTION; - this.pipeline.clearBuffers(bg.base.ClearBuffers.DEPTH); - sceneRoot.accept(this.drawVisitor); - this.pipeline.opacityLayer = opacityLayer; - - let buffer = this.pipeline.renderSurface.readBuffer(new bg.Viewport(mousePosition.x, mousePosition.y,1,1)); - let pickId = { - r: buffer[3], - g: buffer[2], - b: buffer[1], - a: buffer[0] - }; - - let findIdVisitor = new FindPickIdVisitor(pickId); - sceneRoot.accept(findIdVisitor); - - if (restorePipeline) { - bg.base.Pipeline.SetCurrent(restorePipeline); - } - if (restoreMatrixState) { - bg.base.MatrixState.SetCurrent(restoreMatrixState); - } - - return findIdVisitor.result; - } - } - - bg.manipulation.MousePicker = MousePicker; - -})(); - -(function() { - - let s_r = 0; - let s_g = 0; - let s_b = 0; - let s_a = 0; - - function incrementIdentifier() { - if (s_r==255) { - s_r = 0; - incG(); - } - else { - ++s_r; - } - } - - function incG() { - if (s_g==255) { - s_g = 0; - incB(); - } - else { - ++s_g; - } - } - - function incB() { - if (s_b==255) { - s_b = 0; - incA(); - } - else { - ++s_b; - } - } - - function incA() { - if (s_a==255) { - s_a = 0; - bg.log("WARNING: Maximum number of picker identifier reached."); - } - else { - ++s_a; - } - } - - function getIdentifier() { - incrementIdentifier(); - return { r:s_r, g:s_g, b:s_g, a:s_a }; - } - - let s_selectMode = false; - - bg.manipulation.SelectableType = { - PLIST:1, - GIZMO:2, - GIZMO_ICON:3 - }; - - let s_selectionIconPlist = null; - function selectionIconPlist() { - if (!s_selectionIconPlist) { - s_selectionIconPlist = bg.scene.PrimitiveFactory.SpherePolyList(this.node.context,0.5); - } - return s_selectionIconPlist; - } - - let g_selectableIcons = [ - "bg.scene.Camera", - "bg.scene.Light", - "bg.scene.Transform", - "bg.scene.TextRect" - ]; - - - class Selectable extends bg.scene.Component { - static SetSelectableIcons(sel) { - g_selectableIcons = sel; - } - - static AddSelectableIcon(sel) { - if (g_selectableIcons.indexOf(sel)==-1) { - g_selectableIcons.push(sel); - } - } - - static RemoveSelectableIcon(sel) { - let index = g_selectableIcons.indexOf(sel); - if (index>=0) { - g_selectableIcons.splice(index,1); - } - } - - static SetSelectMode(m) { s_selectMode = m; } - - static GetIdentifier() { return getIdentifier(); } - - constructor() { - super(); - this._initialized = false; - this._selectablePlist = []; - } - - clone() { - return new Selectable(); - } - - buildIdentifier() { - this._initialized = false; - this._selectablePlist = []; - } - - findId(id) { - let result = null; - this._selectablePlist.some((item) => { - if (item.id.r==id.r && item.id.g==id.g && item.id.b==id.b && item.id.a==id.a) { - result = item; - return true; - } - }); - return result; - } - - frame(delta) { - if (!this._initialized && this.drawable) { - this.drawable.forEach((plist,material) => { - let id = getIdentifier(); - this._selectablePlist.push({ - id:id, - type:bg.manipulation.SelectableType.PLIST, - plist:plist, - material:material, - drawable:this.drawable, - node:this.node - }); - }); - this._initialized = true; - } - else if (!this._initialized) { - // Use icon to pick item - let id = getIdentifier(); - this._selectablePlist.push({ - id:id, - type:bg.manipulation.SelectableType.GIZMO_ICON, - plist:null, - material:null, - drawable:null, - node:this.node - }); - this._initialized = true; - } - } - - display(pipeline,matrixState) { - if (pipeline.effect instanceof bg.manipulation.ColorPickEffect && - pipeline.opacityLayer & bg.base.OpacityLayer.SELECTION) - { - let selectableByIcon = g_selectableIcons.some((componentType) => { - return this.node.component(componentType)!=null; - }); - this._selectablePlist.forEach((item) => { - let pickId = new bg.Color(item.id.a/255,item.id.b/255,item.id.g/255,item.id.r/255); - if (item.plist && item.plist.visible) { - // The RGBA values are inverted because the alpha channel must be major than zero to - // produce any output in the framebuffer - pipeline.effect.pickId = pickId; - pipeline.draw(item.plist); - } - else if (!item.plist && selectableByIcon) { - let s = matrixState.cameraDistanceScale * 0.1; - pipeline.effect.pickId = pickId; - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.scale(s,s,s); - pipeline.draw(selectionIconPlist.apply(this)); - matrixState.modelMatrixStack.pop(); - } - }); - } - } - } - - bg.scene.registerComponent(bg.manipulation,Selectable,"bg.manipulation.Selectable"); -})(); -(function() { - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class BorderDetectionEffect extends bg.base.TextureEffect { - constructor(context) { - super(context); - - let vertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - let fragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - vertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - { name:"fsTexCoord", dataType:"vec2", role:"out" } - ]); - - fragment.addParameter([ - lib().inputs.material.texture, - { name:"inTexSize", dataType:"vec2", role:"value" }, - { name:"inConvMatrix", dataType:"float", role:"value", vec:9 }, - { name:"inBorderColor", dataType:"vec4", role:"value" }, - { name:"inBorderWidth", dataType:"float", role:"value" }, - { name:"fsTexCoord", dataType:"vec2", role:"in" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - vertex.setMainBody(` - gl_Position = vec4(inVertex,1.0); - fsTexCoord = inTex0; - `); - fragment.addFunction(lib().functions.utils.applyConvolution); - fragment.setMainBody(` - vec4 selectionColor = applyConvolution(inTexture,fsTexCoord,inTexSize,inConvMatrix,inBorderWidth); - if (selectionColor.r!=0.0 && selectionColor.g!=0.0 && selectionColor.b!=0.0) { - gl_FragColor = inBorderColor; - } - else { - discard; - } - `); - } - - this.setupShaderSource([ - vertex, - fragment - ]); - - this._highlightColor = bg.Color.White(); - this._borderWidth = 2; - } - - get highlightColor() { return this._highlightColor; } - set highlightColor(c) { this._highlightColor = c; } - - get borderWidth() { return this._borderWidth; } - set borderWidth(w) { this._borderWidth = w; } - - setupVars() { - let texture = null; - if (this._surface instanceof bg.base.Texture) { - texture = this._surface; - } - else if (this._surface instanceof bg.base.RenderSurface) { - texture = this._surface.getTexture(0); - } - - if (texture) { - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2("inTexSize",texture.size); - } - - let convMatrix = [ - 0, 1, 0, - 1,-4, 1, - 0, 1, 0 - ]; - this.shader.setValueFloatPtr("inConvMatrix",convMatrix); - this.shader.setVector4("inBorderColor", this._highlightColor); - this.shader.setValueFloat("inBorderWidth", this._borderWidth); - } - } - - bg.manipulation.BorderDetectionEffect = BorderDetectionEffect; - - let s_plainColorVertex = null; - let s_plainColorFragment = null; - - function plainColorVertex() { - if (!s_plainColorVertex) { - s_plainColorVertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_plainColorVertex.addParameter(lib().inputs.buffers.vertex); - s_plainColorVertex.addParameter(lib().inputs.matrix.all); - - if (bg.Engine.Get().id=="webgl1") { - s_plainColorVertex.setMainBody(` - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - `); - } - } - return s_plainColorVertex; - } - - function plainColorFragment() { - if (!s_plainColorFragment) { - s_plainColorFragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - s_plainColorFragment.addParameter([ - { name:"inColor", dataType:"vec4", role:"value" }, - { name:"inSelectMode", dataType:"int", role:"value" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_plainColorFragment.setMainBody(` - if (inSelectMode==0) { - discard; - } - else { - gl_FragColor = inColor; - } - `); - } - } - return s_plainColorFragment; - } - - class PlainColorEffect extends bg.base.Effect { - constructor(context) { - super(context); - - let sources = [ - plainColorVertex(), - plainColorFragment() - ]; - this.setupShaderSource(sources); - } - - beginDraw() { - bg.Math.seed = 1; - } - - setupVars() { - this._baseColor = new bg.Color(bg.Math.seededRandom(),bg.Math.seededRandom(),bg.Math.seededRandom(),1); - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - this.shader.setMatrix4('inModelMatrix',matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4('inViewMatrix',viewMatrix); - this.shader.setMatrix4('inProjectionMatrix',matrixState.projectionMatrixStack.matrixConst); - this.shader.setVector4('inColor', this._baseColor); - this.shader.setValueInt("inSelectMode", this.material.selectMode); - } - } - - bg.manipulation.PlainColorEffect = PlainColorEffect; - - function buildOffscreenPipeline() { - let offscreenPipeline = new bg.base.Pipeline(this.context); - - let renderSurface = new bg.base.TextureSurface(this.context); - offscreenPipeline.effect = new bg.manipulation.PlainColorEffect(this.context); - let colorAttachments = [ - { type:bg.base.RenderSurfaceType.RGBA, format:bg.base.RenderSurfaceFormat.UNSIGNED_BYTE }, - { type:bg.base.RenderSurfaceType.DEPTH, format:bg.base.RenderSurfaceFormat.RENDERBUFFER } - ]; - renderSurface.create(colorAttachments); - offscreenPipeline.renderSurface = renderSurface; - - return offscreenPipeline; - } - - class SelectionHighlight extends bg.app.ContextObject { - - constructor(context) { - super(context); - - this._offscreenPipeline = buildOffscreenPipeline.apply(this); - - this._pipeline = new bg.base.Pipeline(this.context); - this._pipeline.textureEffect = new bg.manipulation.BorderDetectionEffect(this.context); - - this._matrixState = new bg.base.MatrixState(); - - this._drawVisitor = new bg.scene.DrawVisitor(this._offscreenPipeline,this._matrixState); - this._drawVisitor.forceDraw = false; - } - - get highlightColor() { return this._pipeline.textureEffect.highlightColor; } - set highlightColor(c) { this._pipeline.textureEffect.highlightColor = c; } - - get borderWidth() { return this._pipeline.textureEffect.borderWidth; } - set borderWidth(w) { this._pipeline.textureEffect.borderWidth = w; } - - get drawInvisiblePolyList() { return this._drawVisitor.forceDraw; } - set drawInvisiblePolyList(d) { this._drawVisitor.forceDraw = d; } - - drawSelection(sceneRoot,camera) { - let restorePipeline = bg.base.Pipeline.Current(); - let restoreMatrixState = bg.base.MatrixState.Current(); - this._offscreenPipeline.viewport = camera.viewport; - this._pipeline.viewport = camera.viewport; - - bg.base.Pipeline.SetCurrent(this._offscreenPipeline); - bg.base.MatrixState.SetCurrent(this._matrixState); - this._offscreenPipeline.clearBuffers(bg.base.ClearBuffers.COLOR | bg.base.ClearBuffers.DEPTH); - this._matrixState.projectionMatrixStack.set(camera.projection); - this._matrixState.viewMatrixStack.set(camera.viewMatrix); - this._matrixState.modelMatrixStack.identity(); - sceneRoot.accept(this._drawVisitor); - - let texture = this._offscreenPipeline.renderSurface.getTexture(0); - bg.base.Pipeline.SetCurrent(this._pipeline); - this._pipeline.blend = true; - this._pipeline.blendMode = bg.base.BlendMode.ADD; - this._pipeline.drawTexture(texture); - - if (restorePipeline) { - bg.base.Pipeline.SetCurrent(restorePipeline); - } - if (restoreMatrixState) { - bg.base.MatrixState.SetCurrent(restoreMatrixState); - } - } - } - - bg.manipulation.SelectionHighlight = SelectionHighlight; - -})(); -(function() { - - let Action = { - ROTATE:0, - PAN:1, - ZOOM:2 - }; - - function getOrbitAction(cameraCtrl) { - let left = bg.app.Mouse.LeftButton(), - middle = bg.app.Mouse.MiddleButton(), - right = bg.app.Mouse.RightButton(); - - switch (true) { - case left==cameraCtrl._rotateButtons.left && - middle==cameraCtrl._rotateButtons.middle && - right==cameraCtrl._rotateButtons.right: - return Action.ROTATE; - case left==cameraCtrl._panButtons.left && - middle==cameraCtrl._panButtons.middle && - right==cameraCtrl._panButtons.right: - return Action.PAN; - case left==cameraCtrl._zoomButtons.left && - middle==cameraCtrl._zoomButtons.middle && - right==cameraCtrl._zoomButtons.right: - return Action.ZOOM; - } - } - - function buildPlist(context,vertex,color) { - let plist = new bg.base.PolyList(context); - let normal = []; - let texCoord0 = []; - let index = []; - let currentIndex = 0; - for (let i=0; i OrbitCameraController.DisableAll(ch)); - } - - static SetUniqueEnabled(orbitCameraController,sceneRoot) { - OrbitCameraController.DisableAll(sceneRoot); - orbitCameraController.enabled = true; - } - - constructor() { - super(); - - this._rotateButtons = { left:true, middle:false, right:false }; - this._panButtons = { left:false, middle:false, right:true }; - this._zoomButtons = { left:false, middle:true, right:false }; - - this._rotation = new bg.Vector2(); - this._distance = 5; - this._center = new bg.Vector3(); - this._rotationSpeed = 0.2; - this._forward = 0; - this._left = 0; - this._wheelSpeed = 1; - this._minFocus = 2; - - this._minPitch = 0.1; - this._maxPitch = 85.0; - this._minDistance = 0.4; - this._maxDistance = 24.0; - - this._maxX = 15; - this._minX = -15; - this._minY = 0.1; - this._maxY = 2.0; - this._maxZ = 15; - this._minZ = -15; - - this._displacementSpeed = 0.1; - - this._enabled = true; - - // Do not serialize/deserialize this: - this._keys = {}; - this._showLimitGizmo = true; - this._limitGizmoColor = bg.Color.Green(); - - // This is used for orthographic projections - this._viewWidth = 50; - - this._lastTouch = []; - } - - clone() { - let result = new OrbitCameraController(); - let compData = {}; - this.serialize(compData,[],""); - result.deserialize(null,compData,""); - return result; - } - - setRotateButtons(left,middle,right) { - this._rotateButtons = { left:left, middle:middle, right:right }; - } - - setPanButtons(left,middle,right) { - this._panButtons = { left:left, middle:middle, right:right }; - } - - setZoomButtons(left,middle,right) { - this._zoomButtons = { left:left, middle:middle, right:right }; - } - - get rotation() { return this._rotation; } - set rotation(r) { this._rotation = r; } - get distance() { return this._distance; } - set distance(d) { this._distance = d; } - get center() { return this._center; } - set center(c) { this._center = c; } - get whellSpeed() { this._wheelSpeed; } - set wheelSpeed(w) { this._wheelSpeed = w; } - - get viewWidth() { return this._viewWidth; } - - get minCameraFocus() { return this._minFocus; } - set minCameraFocus(f) { this._minFocus = f; } - get minPitch() { return this._minPitch; } - set minPitch(p) { this._minPitch = p; } - get maxPitch() { return this._maxPitch; } - set maxPitch(p) { this._maxPitch = p; } - get minDistance() { return this._minDistance; } - set minDistance(d) { this._minDistance = d; } - get maxDistance() { return this._maxDistance; } - set maxDistance(d) { this._maxDistance = d; } - - get minX() { return this._minX; } - get maxX() { return this._maxX; } - get minY() { return this._minY; } - get maxY() { return this._maxY; } - get minZ() { return this._minZ; } - get maxZ() { return this._maxZ; } - - set minX(val) { this._minX = val; } - set maxX(val) { this._maxX = val; } - set minY(val) { this._minY = val; } - set maxY(val) { this._maxY = val; } - set minZ(val) { this._minZ = val; } - set maxZ(val) { this._maxZ = val; } - - get displacementSpeed() { return this._displacementSpeed; } - set displacementSpeed(s) { this._displacementSpeed = s; } - - get enabled() { return this._enabled; } - set enabled(e) { this._enabled = e; } - - get showLimitGizmo() { return this._showLimitGizmo; } - set showLimitGizmo(l) { this._showLimitGizmo = l; } - get limitGizmoColor() { return this._limitGizmoColor; } - set limitGizmoColor(c) { this._limitGizmoColor = c; } - - displayGizmo(pipeline,matrixState) { - if (!this._showLimitGizmo) return; - let plist = getGizmo.apply(this); - matrixState.modelMatrixStack.push(); - matrixState.modelMatrixStack.identity(); - if (plist) { - pipeline.draw(plist); - } - matrixState.modelMatrixStack.pop(); - } - - serialize(componentData,promises,url) { - super.serialize(componentData,promises,url); - componentData.rotateButtons = this._rotateButtons; - componentData.panButtons = this._panButtons; - componentData.zoomButtons = this._zoomButtons; - componentData.rotation = this._rotation.toArray(); - componentData.distance = this._distance; - componentData.center = this._center.toArray(); - componentData.rotationSpeed = this._rotationSpeed; - componentData.forward = this._forward; - componentData.left = this._left; - componentData.wheelSpeed = this._wheelSpeed; - componentData.minFocus = this._minFocus; - componentData.minPitch = this._minPitch; - componentData.maxPitch = this._maxPitch; - componentData.minDistance = this._minDistance; - componentData.maxDistance = this._maxDistance; - componentData.maxX = this._maxX; - componentData.minX = this._minX; - componentData.minY = this._minY; - componentData.maxY = this._maxY; - componentData.maxZ = this._maxZ; - componentData.minZ = this._minZ; - componentData.displacementSpeed = this._displacementSpeed; - componentData.enabled = this._enabled; - } - - deserialize(context,componentData,url) { - this._rotateButtons = componentData.rotateButtons || this._rotateButtons; - this._panButtons = componentData.panButtons || this._panButtons; - this._zoomButtons = componentData.zoomButtons || this._zoomButtons; - this._rotation = new bg.Vector2(componentData.rotation) || this._rotation; - this._distance = componentData.distance!==undefined ? componentData.distance : this._distance; - this._center = new bg.Vector3(componentData.center) || this._center; - this._rotationSpeed = componentData.rotationSpeed!==undefined ? componentData.rotationSpeed : this._rotationSpeed; - this._forward = componentData.forward!==undefined ? componentData.forward : this._forward; - this._left = componentData.left!==undefined ? componentData.left : this._left; - this._wheelSpeed = componentData.wheelSpeed!==undefined ? componentData.wheelSpeed : this._wheelSpeed; - this._minFocus = componentData.minFocus!==undefined ? componentData.minFocus : this._minFocus; - this._minPitch = componentData.minPitch!==undefined ? componentData.minPitch : this._minPitch; - this._maxPitch = componentData.maxPitch!==undefined ? componentData.maxPitch : this._maxPitch; - this._minDistance = componentData.minDistance!==undefined ? componentData.minDistance : this._minDistance; - this._maxDistance = componentData.maxDistance!==undefined ? componentData.maxDistance : this._maxDistance; - this._maxX = componentData.maxX!==undefined ? componentData.maxX : this._maxX; - this._minX = componentData.minX!==undefined ? componentData.minX : this._minX; - this._minY = componentData.minY!==undefined ? componentData.minY : this._minY; - this._maxY = componentData.maxY!==undefined ? componentData.maxY : this._maxY; - this._maxZ = componentData.maxZ!==undefined ? componentData.maxZ : this._maxZ; - this._minZ = componentData.minZ!==undefined ? componentData.minZ : this._minZ; - this._displacementSpeed = componentData.displacementSpeed!==undefined ? componentData.displacementSpeed : this._displacementSpeed; - this._enabled = componentData.enabled!==undefined ? componentData.enabled : this._enabled; - } - - frame(delta) { - let orthoStrategy = this.camera && typeof(this.camera.projectionStrategy)=="object" && - this.camera.projectionStrategy instanceof bg.scene.OrthographicProjectionStrategy ? - this.camera.projectionStrategy : null; - - - if (this.transform && this.enabled) { - let forward = this.transform.matrix.forwardVector; - let left = this.transform.matrix.leftVector; - forward.scale(this._forward); - left.scale(this._left); - this._center.add(forward).add(left); - - let pitch = this._rotation.x>this._minPitch ? this._rotation.x:this._minPitch; - pitch = pitchthis._minDistance ? this._distance:this._minDistance; - this._distance = this._distancethis._maxX) this._center.x = this._maxX; - - if (this._center.ythis._maxY) this._center.y = this._maxY; - - if (this._center.zthis._maxZ) this._center.z = this._maxZ; - - this.transform.matrix - .identity() - .translate(this._center) - .rotate(bg.Math.degreesToRadians(this._rotation.y), 0,1,0) - .rotate(bg.Math.degreesToRadians(pitch), -1,0,0); - - if (orthoStrategy) { - orthoStrategy.viewWidth = this._viewWidth; - } - else { - this.transform.matrix.translate(0,0,this._distance); - } - } - - if (this.camera) { - this.camera.focus = this._distance>this._minFocus ? this._distance:this._minFocus; - - } - } - - mouseDown(evt) { - if (!this.enabled) return; - this._mouseButtonPressed = true; - this._lastPos = new bg.Vector2(evt.x,evt.y); - } - - mouseUp(evt) { - this._mouseButtonPressed = false; - } - - mouseDrag(evt) { - if (this.transform && this._lastPos && this.enabled) { - let delta = new bg.Vector2(this._lastPos.y - evt.y, - this._lastPos.x - evt.x); - this._lastPos.set(evt.x,evt.y); - let orthoStrategy = this.camera && typeof(this.camera.projectionStrategy)=="object" && - this.camera.projectionStrategy instanceof bg.scene.OrthographicProjectionStrategy ? - true : false; - - switch (getOrbitAction(this)) { - case Action.ROTATE: - delta.x = delta.x * -1; - this._rotation.add(delta.scale(0.5)); - break; - case Action.PAN: - let up = this.transform.matrix.upVector; - let left = this.transform.matrix.leftVector; - - if (orthoStrategy) { - up.scale(delta.x * -0.0005 * this._viewWidth); - left.scale(delta.y * -0.0005 * this._viewWidth); - } - else { - up.scale(delta.x * -0.001 * this._distance); - left.scale(delta.y * -0.001 * this._distance); - } - this._center.add(up).add(left); - break; - case Action.ZOOM: - this._distance += delta.x * 0.01 * this._distance; - this._viewWidth += delta.x * 0.01 * this._viewWidth; - if (this._viewWidth<0.5) this._viewWidth = 0.5; - break; - } - } - } - - mouseWheel(evt) { - if (!this.enabled) return; - let mult = this._distance>0.01 ? this._distance:0.01; - let wMult = this._viewWidth>1 ? this._viewWidth:1; - this._distance += evt.delta * 0.001 * mult * this._wheelSpeed; - this._viewWidth += evt.delta * 0.0001 * wMult * this._wheelSpeed; - if (this._viewWidth<0.5) this._viewWidth = 0.5; - } - - touchStart(evt) { - if (!this.enabled) return; - this._lastTouch = evt.touches; - } - - touchMove(evt) { - if (this._lastTouch.length==evt.touches.length && this.transform && this.enabled) { - if (this._lastTouch.length==1) { - // Rotate - let last = this._lastTouch[0]; - let t = evt.touches[0]; - let delta = new bg.Vector2((last.y - t.y) * -1.0, last.x - t.x); - - this._rotation.add(delta.scale(0.5)); - } - else if (this._lastTouch.length==2) { - // Pan/zoom - let l0 = this._lastTouch[0]; - let l1 = this._lastTouch[1]; - let t0 = null; - let t1 = null; - evt.touches.forEach((touch) => { - if (touch.identifier==l0.identifier) { - t0 = touch; - } - else if (touch.identifier==l1.identifier) { - t1 = touch; - } - }); - let dist0 = Math.round((new bg.Vector2(l0.x,l0.y)).sub(new bg.Vector3(l1.x,l1.y)).magnitude()); - let dist1 = Math.round((new bg.Vector2(t0.x,t0.y)).sub(new bg.Vector3(t1.x,t1.y)).magnitude()); - let delta = new bg.Vector2(l0.y - t0.y, l1.x - t1.x); - let up = this.transform.matrix.upVector; - let left = this.transform.matrix.leftVector; - - up.scale(delta.x * -0.001 * this._distance); - left.scale(delta.y * -0.001 * this._distance); - this._center.add(up).add(left); - - this._distance += (dist0 - dist1) * 0.005 * this._distance; - } - } - this._lastTouch = evt.touches; - } - - keyDown(evt) { - if (!this.enabled) return; - this._keys[evt.key] = true; - bg.app.MainLoop.singleton.windowController.postRedisplay(); - } - - keyUp(evt) { - if (!this.enabled) return; - this._keys[evt.key] = false; - } - } - - class FPSCameraController extends bg.scene.Component { - - } - - class TargetCameraController extends bg.scene.Component { - - } - - bg.scene.registerComponent(bg.manipulation,OrbitCameraController,"bg.manipulation.OrbitCameraController"); - bg.scene.registerComponent(bg.manipulation,FPSCameraController,"bg.manipulation.FPSCameraController"); - bg.scene.registerComponent(bg.manipulation,TargetCameraController,"bg.manipulation.TargetCameraController"); - -})(); - -bg.tools = { - -}; - -(function() { - class BoundingBox { - constructor(drawableOrPlist, transformMatrix) { - this._min = new bg.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE); - this._max = new bg.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE); - this._center = null; - this._size = null; - this._halfSize = null; - - this._vertexArray = []; - transformMatrix = transformMatrix || bg.Matrix4.Identity(); - if (drawableOrPlist instanceof bg.scene.Drawable) { - this.addDrawable(drawableOrPlist,transformMatrix); - } - else if (drawableOrPlist instanceof bg.scene.PolyList) { - this.addPolyList(drawableOrPlist,transformMatrix); - } - } - - clear() { - this._min = bg.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE); - this._max = bg.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE); - this._center = this._size = this._halfSize = null; - } - - get min() { return this._min; } - get max() { return this._max; } - get center() { - if (!this._center) { - let s = this.halfSize; - this._center = bg.Vector3.Add(this.halfSize, this._min); - } - return this._center; - } - - get size() { - if (!this._size) { - this._size = bg.Vector3.Sub(this.max, this.min); - } - return this._size; - } - - get halfSize() { - if (!this._halfSize) { - this._halfSize = new bg.Vector3(this.size); - this._halfSize.scale(0.5); - } - return this._halfSize; - } - - addPolyList(polyList, trx) { - this._center = this._size = this._halfSize = null; - for (let i = 0; ithis._max.x) this._max.x = vec.x; - if (vec.z>this._max.z) this._max.z = vec.z; - if (vec.y>this._max.y) this._max.y = vec.y; - } - } - - addDrawable(drawable, trxBase) { - drawable.forEach((plist,mat,elemTrx) => { - if (plist.visible) { - let trx = new bg.Matrix4(trxBase); - if (elemTrx) trx.mult(elemTrx); - this.addPolyList(plist,trx); - } - }); - } - } - - bg.tools.BoundingBox = BoundingBox; -})(); -(function() { - function createCanvas(width,height) { - let result = document.createElement("canvas"); - result.width = width; - result.height = height; - result.style.width = width + "px"; - result.style.height = height + "px"; - return result; - } - - function resizeCanvas(canvas,w,h) { - canvas.width = w; - canvas.height = h; - canvas.style.width = w + 'px'; - canvas.style.height = h + 'px'; - } - - let g_texturePreventRemove = []; - - class CanvasTexture extends bg.app.ContextObject { - - constructor(context,width,height,drawCallback) { - super(context); - - this._canvas = createCanvas(width,height); - - this._drawCallback = drawCallback; - - this._drawCallback(this._canvas.getContext("2d",{preserverDrawingBuffer:true}),this._canvas.width,this._canvas.height); - this._texture = bg.base.Texture.FromCanvas(context,this._canvas); - } - - get width() { return this._canvas.width; } - get height() { return this._canvas.height; } - get canvas() { return this._canvas; } - get texture() { return this._texture; } - - resize(w,h) { - resizeCanvas(this._canvas,w,h); - this.update(); - } - - update() { - this._drawCallback(this._canvas.getContext("2d",{preserverDrawingBuffer:true}),this.width,this.height); - - bg.base.Texture.UpdateCanvasImage(this._texture,this._canvas); - } - } - - bg.tools.CanvasTexture = CanvasTexture; -})(); -(function() { - - bg.tools = bg.tools || {}; - - function packUVs(rect, t1, t2, uvs, pad) { - let hpad = pad / 2; - uvs[t1.uv0.x] = rect.left + pad; uvs[t1.uv0.y] = rect.top + hpad; - uvs[t1.uv1.x] = rect.right - hpad; uvs[t1.uv1.y] = rect.top + hpad; - uvs[t1.uv2.x] = rect.right - hpad; uvs[t1.uv2.y] = rect.bottom - pad; - - if (t2) { - uvs[t2.uv0.x] = rect.right - pad; uvs[t2.uv0.y] = rect.bottom - hpad; - uvs[t2.uv1.x] = rect.left + hpad; uvs[t2.uv1.y] = rect.bottom - hpad; - uvs[t2.uv2.x] = rect.left + hpad; uvs[t2.uv2.y] = rect.top + pad; - } - } - - - function atlasPolyList(vertex,index,padding=0) { - let triangles = []; - let uv = []; - - for (let i=0; i { - let numTriangles = (polyList.index.length / 3); - // Avoid two poly list to share one quad - if (numTriangles%2!=0) numTriangles++; - triangleCount += numTriangles; - }); - let numQuads = triangleCount / 2; - let rows = numQuads, cols = Math.round(Math.sqrt(numQuads)); - while (rows%cols) { - cols--; - } - - rows = cols; - cols = numQuads / cols; - return { - rows: rows, - cols: cols, - triangleCount: triangleCount, - quadSize: { - width: 1 / cols, - height: 1 / rows - }, - currentRow:0, - currentCol:0, - nextRect:function() { - let rect = { - left: this.quadSize.width * this.currentCol, - top: this.quadSize.height * this.currentRow, - right: this.quadSize.width * this.currentCol + this.quadSize.width, - bottom: this.quadSize.height * this.currentRow + this.quadSize.height - }; - if (this.currentCol=this.rows) { - this.currentRow = 0; - } - return rect; - } - }; - } - - function atlasDrawable(drawable,padding) { - let quadData = generateLightmapQuads(drawable); - quadData.currentRow = 0; - quadData.currentCol = 0; - - drawable.forEach((polyList) => { - if (polyList.texCoord1.length>0) return; - let triangles = []; - let uv = []; - for (let i=0; i { - this.matrixState.modelMatrixStack.push(); - this.matrixState.viewMatrixStack.push(); - queue.forEach((objectData) => { - this.matrixState.modelMatrixStack.set(objectData.modelMatrix); - this.matrixState.viewMatrixStack.set(objectData.viewMatrix); - pipeline.effect.material = objectData.material; - pipeline.draw(objectData.plist); - }); - this.matrixState.modelMatrixStack.pop(); - this.matrixState.viewMatrixStack.pop(); - } - - bg.base.Pipeline.SetCurrent(this._gbufferUbyte); - this._gbufferUbyte.viewport = camera.viewport; - this._gbufferUbyte.clearBuffers(); - performRenderQueue(activeQueue,this._gbufferUbyte); - - bg.base.Pipeline.SetCurrent(this._gbufferFloat); - this._gbufferFloat.viewport = camera.viewport; - this._gbufferFloat.clearBuffers(); - performRenderQueue(activeQueue,this._gbufferFloat); - - // Render lights - this._lighting.viewport = camera.viewport; - this._lighting.clearcolor = bg.Color.White(); - bg.base.Pipeline.SetCurrent(this._lighting); - this._lighting.clearBuffers(bg.base.ClearBuffers.COLOR_DEPTH); - this._lighting.blendMode = bg.base.BlendMode.ADD; - this._lighting.blend = true; - this._shadow.viewport = camera.viewport; - - let lightIndex = 0; - bg.scene.Light.GetActiveLights().forEach((lightComponent) => { - if (lightComponent.light && lightComponent.light.enabled && - lightComponent.node && lightComponent.node.enabled) - { - if (lightComponent.light.type==bg.base.LightType.DIRECTIONAL) - { - this._shadowMap.update(scene,camera,lightComponent.light,lightComponent.transform,bg.base.ShadowCascade.NEAR); - - bg.base.Pipeline.SetCurrent(this._shadow); - this._shadow.viewport = camera.viewport; - this._shadow.clearBuffers(); - this._shadow.effect.light = lightComponent.light; - this._shadow.effect.shadowMap = this._shadowMap; - scene.accept(this.shadowVisitor); - } - else if (lightComponent.light.type==bg.base.LightType.SPOT) { - this._shadowMap.shadowType = this.settings.shadows.type; - this._shadowMap.update(scene,camera,lightComponent.light,lightComponent.transform); - bg.base.Pipeline.SetCurrent(this._shadow); - this._shadow.viewport = camera.viewport; - this._shadow.clearBuffers(); - this._shadow.effect.light = lightComponent.light; - this._shadow.effect.shadowMap = this._shadowMap; - scene.accept(this.shadowVisitor); - } - - bg.base.Pipeline.SetCurrent(this._lighting); - // Only render light emission in the first light source - this._lighting.textureEffect.lightEmissionFactor = lightIndex==0 ? 10:0; - - this._lighting.textureEffect.light = lightComponent.light; - this._lighting.textureEffect.lightTransform = lightComponent.transform; - this._lighting.textureEffect.shadowMap = this.maps.shadow; - this._lighting.drawTexture(this.maps); - ++lightIndex; - } - }); - - let renderSSAO = this.settings.ambientOcclusion.enabled; - let renderSSRT = this.settings.raytracer.enabled; - let vp = new bg.Viewport(camera.viewport); - - this._ssao.textureEffect.enabled = renderSSAO; - this._ssao.textureEffect.settings.kernelSize = this.settings.ambientOcclusion.kernelSize; - this._ssao.textureEffect.settings.sampleRadius = this.settings.ambientOcclusion.sampleRadius; - this._ssao.textureEffect.settings.maxDistance = this.settings.ambientOcclusion.maxDistance; - if (renderSSAO) { - bg.base.Pipeline.SetCurrent(this._ssao); - this._ssao.viewport = new bg.Viewport(vp.x,vp.y,vp.width * g_ssaoScale, vp.height * g_ssaoScale); - this._ssao.clearBuffers(); - this._ssao.textureEffect.viewport = camera.viewport; - this._ssao.textureEffect.projectionMatrix = camera.projection; - this._ssao.drawTexture(this.maps); - } - - - // SSRT - bg.base.Pipeline.SetCurrent(this._ssrt); - if (renderSSRT) { - this._ssrt.viewport = new bg.Viewport(vp.x,vp.y,vp.width * g_ssrtScale, vp.height * g_ssrtScale); - this._ssrt.clearBuffers(bg.base.ClearBuffers.DEPTH); - this._ssrt.textureEffect.quality = this.settings.raytracer.quality; - var cameraTransform = camera.node.component("bg.scene.Transform"); - if (cameraTransform) { - let viewProjection = new bg.Matrix4(camera.projection); - viewProjection.mult(camera.viewMatrix); - this._ssrt.textureEffect.cameraPosition= viewProjection.multVector(cameraTransform.matrix.position).xyz; - } - this._ssrt.textureEffect.projectionMatrix = camera.projection; - this._ssrt.textureEffect.rayFailColor = this.settings.raytracer.clearColor || bg.Color.Black(); - this._ssrt.textureEffect.basic = this.settings.raytracer.basicReflections || false; - this._ssrt.textureEffect.viewportSize = new bg.Vector2(this._ssrt.viewport.width,this._ssrt.viewport.height); - this._ssrt.drawTexture(this.maps); - } - - bg.base.Pipeline.SetCurrent(this.pipeline); - this.pipeline.viewport = camera.viewport; - this.pipeline.clearBuffers(); - this.pipeline.textureEffect.viewport = camera.viewport; - this.pipeline.textureEffect.ssaoBlur = renderSSAO ? this.settings.ambientOcclusion.blur : 1; - - this.pipeline.textureEffect.ssrtScale = g_ssrtScale * this.settings.renderScale; - this.pipeline.drawTexture({ - lightingMap:this.maps.lighting, - diffuseMap:this.maps.diffuse, - positionMap:this.maps.position, - ssaoMap:renderSSAO ? this.maps.ambientOcclusion:bg.base.TextureCache.WhiteTexture(this.context), - reflectionMap:renderSSRT ? this.maps.reflection:this.maps.lighting, - specularMap:this.maps.specular, - materialMap:this.maps.material, - opaqueDepthMap:this.maps.mixDepthMap, - shininess:this.maps.shininess - // TODO: bloom - }); // null: all textures are specified as parameters to the effect - - camera.viewport = vp; - } - } - - bg.render.DeferredRenderLayer = DeferredRenderLayer; - -})(); - -(function() { - - - - class DeferredRenderer extends bg.render.Renderer { - constructor(context) { - super(context); - this._size = new bg.Size2D(0); - } - - get isSupported() { - return bg.base.RenderSurface.MaxColorAttachments()>5 && - bg.base.RenderSurface.SupportFormat(bg.base.RenderSurfaceFormat.FLOAT) && - bg.base.RenderSurface.SupportType(bg.base.RenderSurfaceType.DEPTH); - } - - get pipeline() { return this._pipeline; } - - create() { - let ctx = this.context; - - this._renderQueueVisitor = new bg.scene.RenderQueueVisitor(); - - this._opaqueLayer = new bg.render.DeferredRenderLayer(ctx); - this._opaqueLayer.settings = this.settings; - this._opaqueLayer.createOpaque(); - - this._transparentLayer = new bg.render.DeferredRenderLayer(ctx); - this._transparentLayer.settings = this.settings; - this._transparentLayer.createTransparent(this._opaqueLayer.maps); - - this._shadowMap = new bg.base.ShadowMap(ctx); - this._shadowMap.size = new bg.Vector2(2048); - - this._opaqueLayer.shadowMap = this._shadowMap; - this._transparentLayer.shadowMap = this._shadowMap; - - let mixSurface = new bg.base.TextureSurface(ctx); - mixSurface.create(); - this._mixPipeline = new bg.base.Pipeline(ctx); - this._mixPipeline.textureEffect = new bg.render.RendererMixEffect(ctx); - this._mixPipeline.renderSurface = mixSurface; - - this._pipeline = new bg.base.Pipeline(ctx); - this._pipeline.textureEffect = new bg.render.PostprocessEffect(ctx); - - this.settings.renderScale = this.settings.renderScale || 1.0; - } - - draw(scene,camera) { - if (this._shadowMap.size.x!=this.settings.shadows.quality) { - this._shadowMap.size = new bg.Vector2(this.settings.shadows.quality); - } - - let vp = camera.viewport; - let aa = this.settings.antialiasing || {}; - let maxSize = aa.maxTextureSize || 4096; - let ratio = vp.aspectRatio; - let scaledWidth = vp.width; - let scaledHeight = vp.height; - if (aa.enabled) { - scaledWidth = vp.width * 2; - scaledHeight = vp.height * 2; - if (ratio>1 && scaledWidth>maxSize) { // Landscape - scaledWidth = maxSize; - scaledHeight = maxSize / ratio; - } - else if (scaledHeight>maxSize) { // Portrait - scaledHeight = maxSize; - scaledWidth = maxSize * ratio; - } - } - else if (true) { - scaledWidth = vp.width * this.settings.renderScale; - scaledHeight = vp.height * this.settings.renderScale; - if (ratio>1 && scaledWidth>maxSize) { // Landscape - scaledWidth = maxSize; - scaledHeight = maxSize / ratio; - } - else if (scaledHeight>maxSize) { // Portrait - scaledHeight = maxSize; - scaledWidth = maxSize * ratio; - } - } - - let scaledViewport = new bg.Viewport(0,0,scaledWidth,scaledHeight); - camera.viewport = scaledViewport; - let mainLight = null; - - this._opaqueLayer.clearColor = this.clearColor; - if (this._size.width!=camera.viewport.width || - this._size.height!=camera.viewport.height) - { - this._opaqueLayer.resize(camera); - this._transparentLayer.resize(camera); - } - - - // Update render queue - this._renderQueueVisitor.modelMatrixStack.identity(); - this._renderQueueVisitor.projectionMatrixStack.push(); - this._renderQueueVisitor.projectionMatrixStack.set(camera.projection); - this._renderQueueVisitor.viewMatrixStack.set(camera.viewMatrix); - this._renderQueueVisitor.renderQueue.beginFrame(camera.worldPosition); - scene.accept(this._renderQueueVisitor); - this._renderQueueVisitor.renderQueue.sortTransparentObjects(); - this._opaqueLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - this._transparentLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - this._renderQueueVisitor.projectionMatrixStack.pop(); - - bg.base.Pipeline.SetCurrent(this._mixPipeline); - this._mixPipeline.viewport = camera.viewport; - this._mixPipeline.clearColor = bg.Color.Black(); - this._mixPipeline.clearBuffers(); - this._mixPipeline.drawTexture({ - opaque:this._opaqueLayer.texture, - transparent:this._transparentLayer.texture, - transparentNormal:this._transparentLayer.maps.normal, - opaqueDepth:this._opaqueLayer.maps.position, - transparentDepth:this._transparentLayer.maps.position - }); - - bg.base.Pipeline.SetCurrent(this.pipeline); - this.pipeline.viewport = vp; - this.pipeline.clearColor = this.clearColor; - this.pipeline.clearBuffers(); - this.pipeline.drawTexture({ - texture: this._mixPipeline.renderSurface.getTexture(0) - }); - camera.viewport = vp; - } - - getImage(scene,camera,width,height) { - let prevViewport = camera.viewport; - camera.viewport = new bg.Viewport(0,0,width,height); - this.draw(scene,camera); - - let canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - let ctx = canvas.getContext('2d'); - - let buffer = this.pipeline.renderSurface.readBuffer(new bg.Viewport(0,0,width,height)); - let imgData = ctx.createImageData(width,height); - let len = width * 4; - // Flip image data - for (let i = 0; i { - this._pipeline.effect.lightArray.push(comp.light,comp.transform); - }); - this._pipeline.effect.shadowMap = this._shadowMap; - } - } - - performDraw(renderQueue,scene,camera) { - this._pipeline.viewport = camera.viewport; - - let activeQueue = this._pipeline.opacityLayer==bg.base.OpacityLayer.OPAQUE ? renderQueue.opaqueQueue : renderQueue.transparentQueue; - this.matrixState.modelMatrixStack.push(); - activeQueue.forEach((objectData) => { - this.matrixState.modelMatrixStack.set(objectData.modelMatrix); - this.matrixState.viewMatrixStack.set(objectData.viewMatrix); - this._pipeline.effect.material = objectData.material; - this._pipeline.draw(objectData.plist); - }); - this.matrixState.modelMatrixStack.pop(); - } - } - - bg.render.ForwardRenderLayer = ForwardRenderLayer; - -})(); - -(function() { - - class ForwardRenderer extends bg.render.Renderer { - constructor(context) { - super(context); - } - - get isSupported() { return true; } - create() { - let ctx = this.context; - this._transparentLayer = new bg.render.ForwardRenderLayer(ctx,bg.base.OpacityLayer.TRANSPARENT); - this._opaqueLayer = new bg.render.ForwardRenderLayer(ctx,bg.base.OpacityLayer.OPAQUE); - this._shadowMap = new bg.base.ShadowMap(ctx); - this._shadowMap.size = new bg.Vector2(2048); - - this.settings.shadows.cascade = bg.base.ShadowCascade.NEAR; - - this._renderQueueVisitor = new bg.scene.RenderQueueVisitor - } - - draw(scene,camera) { - let shadowLight = null; - let lightSources = []; - bg.scene.Light.GetActiveLights().some((lightComponent,index) => { - if (index>=bg.base.MAX_FORWARD_LIGHTS) return true; - if (lightComponent.light && - lightComponent.light.enabled && - lightComponent.node && - lightComponent.node.enabled) - { - lightSources.push(lightComponent); - if (lightComponent.light.type!=bg.base.LightType.POINT && lightComponent.light.castShadows) { - shadowLight = lightComponent; - } - } - }); - - if (shadowLight) { - if (this._shadowMap.size.x!=this.settings.shadows.quality) { - this._shadowMap.size = new bg.Vector2(this.settings.shadows.quality); - } - this._shadowMap.update(scene,camera,shadowLight.light,shadowLight.transform,this.settings.shadows.cascade); - } - if (lightSources.length) { - this._opaqueLayer.setLightSources(lightSources); - this._opaqueLayer.shadowMap = this._shadowMap; - - this._transparentLayer.setLightSources(lightSources); - this._transparentLayer.shadowMap = this._shadowMap; - } - else { - this._opaqueLayer.setLightSources([]); - this._opaqueLayer.shadowMap = null; - this._transparentLayer.setLightSources([]); - this._transparentLayer.shadowMap = null; - } - - // Update render queue - this._renderQueueVisitor.projectionMatrixStack.set(camera.projection); - this._renderQueueVisitor.modelMatrixStack.identity(); - this._renderQueueVisitor.viewMatrixStack.set(camera.viewMatrix); - this._renderQueueVisitor.renderQueue.beginFrame(camera.worldPosition); - scene.accept(this._renderQueueVisitor); - this._renderQueueVisitor.renderQueue.sortTransparentObjects(); - - this._opaqueLayer.pipeline.clearColor = this.clearColor; - this._opaqueLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - this._transparentLayer.draw(this._renderQueueVisitor.renderQueue,scene,camera); - } - - getImage(scene,camera,width,height) { - let prevViewport = camera.viewport; - camera.viewport = new bg.Viewport(0,0,width,height); - this.draw(scene,camera); - this.draw(scene,camera); - - let canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - let ctx = canvas.getContext('2d'); - - let buffer = this._opaqueLayer.pipeline.renderSurface.readBuffer(new bg.Viewport(0,0,width,height)); - let imgData = ctx.createImageData(width,height); - let len = width * 4; - // Flip image data - for (let i = 0; i=inAlphaCutoff) { - vec3 normal = samplerNormal(inNormalMap,fsTex0Coord,inNormalMapOffset,inNormalMapScale); - normal = combineNormalWithMap(fsNormal,fsTangent,fsBitangent,normal); - vec4 specular = specularColor(inSpecularColor,inShininessMask,fsTex0Coord,inTextureOffset,inTextureScale, - inShininessMaskChannel,inShininessMaskInvert); - float lightEmission = applyTextureMask(inLightEmission, - inLightEmissionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inLightEmissionMaskChannel,inLightEmissionMaskInvert); - - float reflectionMask = applyTextureMask(inReflection, - inReflectionMask,fsTex0Coord,inTextureOffset,inTextureScale, - inReflectionMaskChannel,inReflectionMaskInvert); - - float roughnessMask = applyTextureMask(inRoughness, - inRoughnessMask,fsTex0Coord,inTextureOffset,inTextureScale, - inRoughnessMaskChannel,inRoughnessMaskInvert); - - gl_FragData[0] = diffuse; - gl_FragData[1] = vec4(specular.rgb,roughnessMask); // Store roughness on A component of specular - if (!gl_FrontFacing) { // Flip the normal if back face - normal *= -1.0; - } - gl_FragData[2] = vec4(normal * 0.5 + 0.5, inUnlit ? 0.0 : 1.0); // Store !unlit parameter on A component of normal - gl_FragData[3] = vec4(lightEmission,inShininess/255.0,reflectionMask,float(inCastShadows)); - } - else { - gl_FragData[0] = vec4(0.0); - gl_FragData[1] = vec4(0.0); - gl_FragData[2] = vec4(0.0); - gl_FragData[3] = vec4(0.0); - discard; - }`); - } - } - return s_ubyteGbufferFragment; - }, - - gbuffer_float_vertex() { - if (!s_floatGbufferVertex) { - s_floatGbufferVertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - - s_floatGbufferVertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - null, - lib().inputs.matrix.model, - lib().inputs.matrix.view, - lib().inputs.matrix.projection, - null, - { name:"fsPosition", dataType:"vec4", role:"out" }, - { name:"fsTex0Coord", dataType:"vec2", role:"out" } - ]); - - if (bg.Engine.Get().id=="webgl1") { - s_floatGbufferVertex.setMainBody(` - fsPosition = inViewMatrix * inModelMatrix * vec4(inVertex,1.0); - fsTex0Coord = inTex0; - - gl_Position = inProjectionMatrix * fsPosition;`); - } - } - return s_floatGbufferVertex; - }, - - gbuffer_float_fragment() { - if (!s_floatGbufferFragment) { - s_floatGbufferFragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - s_floatGbufferFragment.addParameter([ - lib().inputs.material.texture, - lib().inputs.material.textureScale, - lib().inputs.material.textureOffset, - lib().inputs.material.alphaCutoff, - null, - { name:"fsPosition", dataType:"vec4", role:"in" }, - { name:"fsTex0Coord", dataType:"vec2", role:"in" } - ]); - - s_floatGbufferFragment.addFunction(lib().functions.materials.samplerColor); - - if (bg.Engine.Get().id=="webgl1") { - s_floatGbufferFragment.setMainBody(` - float alpha = samplerColor(inTexture,fsTex0Coord,inTextureOffset,inTextureScale).a; - if (alpha0.0) { - float refractionFactor = inRefractionAmount / texture2D(inTransparentDepth,fsTexCoord).z; - vec2 offset = fsTexCoord - normal.xy * refractionFactor; - vec4 opaqueDepth = texture2D(inOpaqueDepth,offset); - vec4 transparentDepth = texture2D(inTransparentDepth,offset); - //if (opaqueDepth.w>transparentDepth.w) { - opaque = texture2D(inOpaque,offset); - //} - } - vec3 color = opaque.rgb * (1.0 - transparent.a) + transparent.rgb * transparent.a; - gl_FragColor = vec4(color, 1.0); - `); - } - } - return this._fragmentShaderSource; - } - - setupVars() { - this.shader.setTexture("inOpaque",this._surface.opaque,bg.base.TextureUnit.TEXTURE_0); - this.shader.setTexture("inTransparent",this._surface.transparent,bg.base.TextureUnit.TEXTURE_1); - this.shader.setTexture("inTransparentNormal",this._surface.transparentNormal,bg.base.TextureUnit.TEXTURE_2); - this.shader.setTexture("inOpaqueDepth",this._surface.opaqueDepth,bg.base.TextureUnit.TEXTURE_3); - this.shader.setTexture("inTransparentDepth",this._surface.transparentDepth,bg.base.TextureUnit.TEXTURE_4); - this.shader.setValueFloat("inRefractionAmount",this.settings.refractionAmount); - } - - get settings() { - if (!this._settings) { - this._currentKernelSize = 0; - this._settings = { - refractionAmount: -0.05 - } - } - return this._settings; - } - - } - - bg.render.RendererMixEffect = RendererMixEffect; -})(); -(function() { - - - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - class ShadowEffect extends bg.base.Effect { - constructor(context) { - super(context); - - let vertex = new bg.base.ShaderSource(bg.base.ShaderType.VERTEX); - let fragment = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - vertex.addParameter([ - lib().inputs.buffers.vertex, - lib().inputs.buffers.tex0, - null, - lib().inputs.matrix.model, - lib().inputs.matrix.view, - lib().inputs.matrix.projection, - { name:"inLightProjectionMatrix", dataType:"mat4", role:"value" }, - { name:"inLightViewMatrix", dataType:"mat4", role:"value" }, - null, - { name:"fsTexCoord", dataType:"vec2", role:"out" }, - { name:"fsVertexPosFromLight", dataType:"vec4", role:"out" } - ]); - - fragment.addParameter(lib().inputs.shadows.all); - fragment.addFunction(lib().functions.utils.unpack); - fragment.addFunction(lib().functions.lighting.getShadowColor); - - fragment.addParameter([ - lib().inputs.material.receiveShadows, - lib().inputs.material.texture, - lib().inputs.material.textureOffset, - lib().inputs.material.textureScale, - lib().inputs.material.alphaCutoff, - null, - { name:"fsTexCoord", dataType:"vec2", role:"in" }, - { name:"fsVertexPosFromLight", dataType:"vec4", role:"in" } - ]); - - fragment.addFunction(lib().functions.materials.samplerColor); - - if (bg.Engine.Get().id=="webgl1") { - vertex.setMainBody(` - mat4 ScaleMatrix = mat4(0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 0.5, 0.0, - 0.5, 0.5, 0.5, 1.0); - - fsVertexPosFromLight = ScaleMatrix * inLightProjectionMatrix * inLightViewMatrix * inModelMatrix * vec4(inVertex,1.0); - fsTexCoord = inTex0; - - gl_Position = inProjectionMatrix * inViewMatrix * inModelMatrix * vec4(inVertex,1.0);`); - - fragment.setMainBody(` - float alpha = samplerColor(inTexture,fsTexCoord,inTextureOffset,inTextureScale).a; - if (alpha>inAlphaCutoff) { - vec4 shadowColor = vec4(1.0, 1.0, 1.0, 1.0); - if (inReceiveShadows) { - shadowColor = getShadowColor(fsVertexPosFromLight,inShadowMap,inShadowMapSize, - inShadowType,inShadowStrength,inShadowBias,inShadowColor); - } - gl_FragColor = shadowColor; - } - else { - discard; - }`); - } - - this.setupShaderSource([ vertex, fragment ]); - } - - beginDraw() { - if (this.light && this.shadowMap) { - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - let lightTransform = this.shadowMap.viewMatrix; - - this.shader.setMatrix4("inLightProjectionMatrix", this.shadowMap.projection); - - this.shader.setMatrix4("inLightViewMatrix",lightTransform); - this.shader.setValueInt("inShadowType",this.shadowMap.shadowType); - this.shader.setTexture("inShadowMap",this.shadowMap.texture,bg.base.TextureUnit.TEXTURE_1); - this.shader.setVector2("inShadowMapSize",this.shadowMap.size); - this.shader.setValueFloat("inShadowStrength",this.light.shadowStrength); - this.shader.setVector4("inShadowColor",this.shadowMap.shadowColor); - this.shader.setValueFloat("inShadowBias",this.light.shadowBias); - } - } - - setupVars() { - if (this.material && this.light) { - let matrixState = bg.base.MatrixState.Current(); - let viewMatrix = new bg.Matrix4(matrixState.viewMatrixStack.matrixConst); - - this.shader.setMatrix4("inModelMatrix",matrixState.modelMatrixStack.matrixConst); - this.shader.setMatrix4("inViewMatrix",viewMatrix); - this.shader.setMatrix4("inProjectionMatrix",matrixState.projectionMatrixStack.matrixConst); - - let texture = this.material.texture || bg.base.TextureCache.WhiteTexture(this.context); - this.shader.setTexture("inTexture",texture,bg.base.TextureUnit.TEXTURE_0); - this.shader.setVector2("inTextureOffset",this.material.textureOffset); - this.shader.setVector2("inTextureScale",this.material.textureScale); - this.shader.setValueFloat("inAlphaCutoff",this.material.alphaCutoff); - - this.shader.setValueInt("inReceiveShadows",this.material.receiveShadows); - } - } - - get material() { return this._material; } - set material(m) { this._material = m; } - - get light() { return this._light; } - set light(l) { this._light = l; } - - get shadowMap() { return this._shadowMap; } - set shadowMap(sm) { this._shadowMap = sm; } - } - - bg.render.ShadowEffect = ShadowEffect; - -})(); -(function() { - function lib() { - return bg.base.ShaderLibrary.Get(); - } - - let MAX_KERN_OFFSETS = 64; - - class SSAOEffect extends bg.base.TextureEffect { - constructor(context) { - super(context); - } - - get fragmentShaderSource() { - if (!this._fragmentShaderSource) { - this._fragmentShaderSource = new bg.base.ShaderSource(bg.base.ShaderType.FRAGMENT); - - this._fragmentShaderSource.addParameter([ - { name:"inViewportSize", dataType:"vec2", role:"value" }, - { name:"inPositionMap", dataType:"sampler2D", role:"value"}, - { name:"inNormalMap", dataType:"sampler2D", role:"value"}, - { name:"inProjectionMatrix", dataType:"mat4", role:"value"}, - { name:"inRandomMap", dataType:"sampler2D", role:"value"}, - { name:"inRandomMapSize", dataType:"vec2", role:"value"}, - { name:"inSampleRadius", dataType:"float", role:"value" }, - { name:"inKernelOffsets", dataType:"vec3", role:"value", vec:MAX_KERN_OFFSETS }, - { name:"inKernelSize", dataType:"int", role:"value" }, - { name:"inSSAOColor", dataType:"vec4", role:"value" }, - { name:"inEnabled", dataType:"bool", role:"value"}, - { name:"inMaxDistance", dataType:"float", role:"value" }, - - { name:"fsTexCoord", dataType:"vec2", role:"in" } // vTexturePosition - ]); - - if (bg.Engine.Get().id=="webgl1") { - this._fragmentShaderSource.setMainBody(` - if (!inEnabled) discard; - else { - vec4 normalTex = texture2D(inNormalMap,fsTexCoord); - vec3 normal = normalTex.xyz * 2.0 - 1.0; - vec4 vertexPos = texture2D(inPositionMap,fsTexCoord); - if (distance(vertexPos.xyz,vec3(0))>inMaxDistance || vertexPos.w==1.0 || normalTex.a==0.0) { - discard; - } - else { - vec2 noiseScale = vec2(inViewportSize.x/inRandomMapSize.x,inViewportSize.y/inRandomMapSize.y); - vec3 randomVector = texture2D(inRandomMap, fsTexCoord * noiseScale).xyz * 2.0 - 1.0; - vec3 tangent = normalize(randomVector - normal * dot(randomVector, normal)); - vec3 bitangent = cross(normal,tangent); - mat3 tbn = mat3(tangent, bitangent, normal); - - float occlusion = 0.0; - for (int i=0; i<${ MAX_KERN_OFFSETS }; ++i) { - if (inKernelSize==i) break; - vec3 samplePos = tbn * inKernelOffsets[i]; - samplePos = samplePos * inSampleRadius + vertexPos.xyz; - - vec4 offset = inProjectionMatrix * vec4(samplePos, 1.0); // -w, w - offset.xyz /= offset.w; // -1, 1 - offset.xyz = offset.xyz * 0.5 + 0.5; // 0, 1 - - vec4 sampleRealPos = texture2D(inPositionMap, offset.xy); - if (samplePos.zMAX_KERN_OFFSETS) { - this.settings.kernelSize = MAX_KERN_OFFSETS; - } - this.shader.setVector2("inViewportSize",new bg.Vector2(this.viewport.width, this.viewport.height)); - - // Surface map parameters - this.shader.setTexture("inPositionMap",this._surface.position,bg.base.TextureUnit.TEXTURE_0); - this.shader.setTexture("inNormalMap",this._surface.normal,bg.base.TextureUnit.TEXTURE_1); - - this.shader.setMatrix4("inProjectionMatrix",this.projectionMatrix); - this.shader.setTexture("inRandomMap",this.randomMap,bg.base.TextureUnit.TEXTURE_2); - this.shader.setVector2("inRandomMapSize",this.randomMap.size); - this.shader.setValueFloat("inSampleRadius",this.settings.sampleRadius); - this.shader.setVector3Ptr("inKernelOffsets",this.kernelOffsets); - this.shader.setValueInt("inKernelSize",this.settings.kernelSize); - this.shader.setVector4("inSSAOColor",this.settings.color); - this.shader.setValueInt("inEnabled",this.settings.enabled); - this.shader.setValueFloat("inMaxDistance",this.settings.maxDistance); - } - - // The following parameters in this effect are required, and the program will crash if - // some of them are not set - get viewport() { return this._viewport; } - set viewport(vp) { this._viewport = vp; } - - get projectionMatrix() { return this._projectionMatrix; } - set projectionMatrix(p) { this._projectionMatrix = p; } - - // randomMap is optional. By default, it takes the default random texture from TextureCache - get randomMap() { - if (!this._randomMap) { - this._randomMap = bg.base.TextureCache.RandomTexture(this.context); - } - return this._randomMap; - } - - set randomMap(rm) { this._randomMap = rm; } - - // Settings: the following parameters are group in a settings object that can be exposed outside - // the renderer object. - get settings() { - if (!this._settings) { - this._currentKernelSize = 0; - this._settings = { - kernelSize: 32, - sampleRadius: 0.3, - color: bg.Color.Black(), - blur: 4, - maxDistance: 100.0, - enabled: true - } - } - return this._settings; - } - - // This parameter is generated automatically using the kernelSize setting - get kernelOffsets() { - if (this._currentKernelSize!=this.settings.kernelSize) { - this._kernelOffsets = []; - for (let i=0; i0.0) { // material[2] is reflectionAmount - vec3 normal = texture2D(inNormalMap,fsTexCoord).xyz * 2.0 - 1.0; - - vec4 specular = texture2D(inSpecularMap,fsTexCoord); - float roughness = specular.a * 0.3; - vec3 r = texture2D(inRandomTexture,fsTexCoord*200.0).xyz * 2.0 - 1.0; - vec3 roughnessFactor = normalize(r) * roughness; - normal = normal + roughnessFactor; - vec4 vertexPos = texture2D(inPositionMap,fsTexCoord); - vec3 cameraVector = vertexPos.xyz - inCameraPos; - vec3 rayDirection = reflect(cameraVector,normal); - vec4 lighting = texture2D(inLightingMap,fsTexCoord); - - vec4 rayFailColor = inRayFailColor; - - vec3 lookup = reflect(cameraVector,normal); - rayFailColor = textureCube(inCubeMap, lookup); - - float increment = ${q.rayIncrement}; - vec4 result = rayFailColor; - if (!inBasicMode) { - result = rayFailColor; - for (float i=0.0; i<${q.maxSamples}.0; ++i) { - if (i==${q.maxSamples}.0) { - break; - } - - float radius = i * increment; - increment *= 1.01; - vec3 ray = vertexPos.xyz + rayDirection * radius; - - vec4 offset = inProjectionMatrix * vec4(ray, 1.0); // -w, w - offset.xyz /= offset.w; // -1, 1 - offset.xyz = offset.xyz * 0.5 + 0.5; // 0, 1 - - vec4 rayActualPos = texture2D(inSamplePosMap, offset.xy); - float hitDistance = rayActualPos.z - ray.z; - if (offset.x>1.0 || offset.y>1.0 || offset.x<0.0 || offset.y<0.0) { - result = rayFailColor; - break; - } - else if (hitDistance>0.02 && hitDistance<0.15) { - result = texture2D(inLightingMap,offset.xy); - break; - } - } - } - if (result.a==0.0) { - gl_FragColor = rayFailColor; - } - else { - gl_FragColor = result; - } - } - else { - discard; - }`); - } - } - return this._fragmentShaderSource; - } - - setupVars() { - this._frameIndex = (this._frameIndex + 1) % 4; - this.shader.setTexture("inPositionMap",this._surface.position,bg.base.TextureUnit.TEXTURE_0); - this.shader.setTexture("inNormalMap",this._surface.normal,bg.base.TextureUnit.TEXTURE_1); - this.shader.setTexture("inLightingMap",this._surface.reflectionColor,bg.base.TextureUnit.TEXTURE_2); - this.shader.setTexture("inMaterialMap",this._surface.material,bg.base.TextureUnit.TEXTURE_3); - this.shader.setTexture("inSamplePosMap",this._surface.reflectionDepth, bg.base.TextureUnit.TEXTURE_4); - this.shader.setMatrix4("inProjectionMatrix",this._projectionMatrix); - this.shader.setVector3("inCameraPos",this._cameraPos); - this.shader.setVector4("inRayFailColor",this.rayFailColor); - this.shader.setValueInt("inBasicMode",this.basic); - this.shader.setValueFloat("inFrameIndex",this._frameIndex); - - this.shader.setTexture("inCubeMap",bg.scene.Cubemap.Current(this.context), bg.base.TextureUnit.TEXTURE_5); - - - if (!this._randomTexture) { - this._randomTexture = bg.base.TextureCache.RandomTexture(this.context,new bg.Vector2(1024)); - } - this.shader.setTexture("inRandomTexture",this._randomTexture, bg.base.TextureUnit.TEXTURE_6); - - this.shader.setTexture("inSpecularMap",this._surface.specular,bg.base.TextureUnit.TEXTURE_7); - } - - get projectionMatrix() { return this._projectionMatrix; } - set projectionMatrix(p) { this._projectionMatrix = p; } - - get cameraPosition() { return this._cameraPos; } - set cameraPosition(c) { this._cameraPos = c; } - - get rayFailColor() { return this._rayFailColor || bg.Color.Black(); } - set rayFailColor(c) { this._rayFailColor = c; } - - get viewportSize() { return this._viewportSize; } - set viewportSize(s) { this._viewportSize = s; } - - get quality() { return this._quality || bg.render.RaytracerQuality.low; } - set quality(q) { - if (!this._quality || this._quality.maxSamples!=q.maxSamples || - this._quality.rayIncrement!=q.rayIncrement) - { - this._quality = q; - this._fragmentShaderSource = null; - this.rebuildShaders(); - } - } - - get basic() { return this._basic; } - set basic(b) { this._basic = b; } - - // TODO: SSRT settings - get settings() { - if (!this._settings) { - } - return this._settings; - } - } - - bg.render.SSRTEffect = SSRTEffect; -})(); -bg.webgl1 = {}; - -(function() { - let WEBGL_1_STRING = "webgl1"; - - bg.webgl1.EngineId = WEBGL_1_STRING; - - class WebGL1Engine extends bg.Engine { - constructor(context) { - super(context); - - // Initialize webgl extensions - bg.webgl1.Extensions.Get(context); - - this._engineId = WEBGL_1_STRING; - this._texture = new bg.webgl1.TextureImpl(context); - this._pipeline = new bg.webgl1.PipelineImpl(context); - this._polyList = new bg.webgl1.PolyListImpl(context); - this._shader = new bg.webgl1.ShaderImpl(context); - this._colorBuffer = new bg.webgl1.ColorRenderSurfaceImpl(context); - this._textureBuffer = new bg.webgl1.TextureRenderSurfaceImpl(context); - this._shaderSource = new bg.webgl1.ShaderSourceImpl(); - } - } - - bg.webgl1.Engine = WebGL1Engine; - -})(); - -(function() { - - bg.webgl1.shaderLibrary = { - inputs:{}, - functions:{} - } - - class ShaderSourceImpl extends bg.base.ShaderSourceImpl { - header(shaderType) { - return "precision highp float;\nprecision highp int;"; - } - - parameter(shaderType,paramData) { - if (!paramData) return "\n"; - let role = ""; - switch (paramData.role) { - case "buffer": - role = "attribute"; - break; - case "value": - role = "uniform"; - break; - case "in": - case "out": - role = "varying"; - break; - } - let vec = ""; - if (paramData.vec) { - vec = `[${paramData.vec}]`; - } - return `${role} ${paramData.dataType} ${paramData.name}${vec};`; - } - - func(shaderType,funcData) { - if (!funcData) return "\n"; - let params = ""; - for (let name in funcData.params) { - params += `${funcData.params[name]} ${name},`; - } - let src = `${funcData.returnType} ${funcData.name}(${params}) {`.replace(',)',')'); - let body = ("\n" + bg.base.ShaderSource.FormatSource(funcData.body)).replace(/\n/g,"\n\t"); - return src + body + "\n}"; - } - } - - bg.webgl1.ShaderSourceImpl = ShaderSourceImpl; - - -})(); -(function() { - let s_singleton = null; - - class Extensions extends bg.app.ContextObject { - static Get(gl) { - if (!s_singleton) { - s_singleton = new Extensions(gl); - } - return s_singleton; - } - - constructor(gl) { - super(gl); - } - - getExtension(ext) { - return this.context.getExtension(ext); - } - - get textureFloat() { - if (this._textureFloat===undefined) { - this._textureFloat = this.getExtension("OES_texture_float"); - } - return this._textureFloat; - } - - get depthTexture() { - if (this._depthTexture===undefined) { - this._depthTexture = this.getExtension("WEBGL_depth_texture"); - } - return this._depthTexture; - } - - get drawBuffers() { - if (this._drawBuffers===undefined) { - this._drawBuffers = this.getExtension("WEBGL_draw_buffers"); - } - return this._drawBuffers; - } - } - - bg.webgl1.Extensions = Extensions; -})(); -(function() { - - class PipelineImpl extends bg.base.PipelineImpl { - initFlags(context) { - bg.base.ClearBuffers.COLOR = context.COLOR_BUFFER_BIT; - bg.base.ClearBuffers.DEPTH = context.DEPTH_BUFFER_BIT; - } - - setViewport(context,vp) { - context.viewport(vp.x,vp.y,vp.width,vp.height); - } - - clearBuffers(context,color,buffers) { - context.clearColor(color.r,color.g,color.b,color.a); - if (buffers) context.clear(buffers); - } - - setDepthTestEnabled(context,e) { - e ? context.enable(context.DEPTH_TEST):context.disable(context.DEPTH_TEST); - } - - setCullFace(context,e) { - e ? context.enable(context.CULL_FACE):context.disable(context.CULL_FACE); - } - - setBlendEnabled(context,e) { - e ? context.enable(context.BLEND):context.disable(context.BLEND); - } - - setBlendMode(gl,m) { - switch (m) { - case bg.base.BlendMode.NORMAL: - gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.MULTIPLY: - gl.blendFunc(gl.ZERO,gl.SRC_COLOR); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.ADD: - gl.blendFunc(gl.ONE,gl.ONE); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.SUBTRACT: - gl.blendFunc(gl.ONE,gl.ONE); - gl.blendEquation(gl.FUNC_SUBTRACT); - break; - case bg.base.BlendMode.ALPHA_ADD: - gl.blendFunc(gl.SRC_ALPHA,gl.SRC_ALPHA); - gl.blendEquation(gl.FUNC_ADD); - break; - case bg.base.BlendMode.ALPHA_SUBTRACT: - gl.blendFunc(gl.SRC_ALPHA,gl.SRC_ALPHA); - gl.blendEquation(gl.FUNC_SUBTRACT); - break; - } - } - } - - bg.webgl1.PipelineImpl = PipelineImpl; -})(); -(function() { - function createBuffer(context,array,itemSize,drawMode) { - let result = null; - if (array.length) { - result = context.createBuffer(); - context.bindBuffer(context.ARRAY_BUFFER,result); - context.bufferData(context.ARRAY_BUFFER, new Float32Array(array), drawMode); - result.itemSize = itemSize; - result.numItems = array.length/itemSize; - } - return result; - } - - function deleteBuffer(context,buffer) { - if (buffer) { - context.deleteBuffer(buffer); - } - return null; - } - - let s_uintElements = false; - - class PolyListImpl extends bg.base.PolyListImpl { - initFlags(context) { - bg.base.DrawMode.TRIANGLES = context.TRIANGLES; - bg.base.DrawMode.TRIANGLE_FAN = context.TRIANGLE_FAN; - bg.base.DrawMode.TRIANGLE_STRIP = context.TRIANGLE_STRIP; - bg.base.DrawMode.LINES = context.LINES; - bg.base.DrawMode.LINE_STRIP = context.LINE_STRIP; - - s_uintElements = context.getExtension("OES_element_index_uint"); - } - - create(context) { - return { - vertexBuffer:null, - normalBuffer:null, - tex0Buffer:null, - tex1Buffer:null, - tex2Buffer:null, - colorBuffer:null, - tangentBuffer:null, - indexBuffer:null - } - } - - build(context,plist,vert,norm,t0,t1,t2,col,tan,index) { - plist.vertexBuffer = createBuffer(context,vert,3,context.STATIC_DRAW); - plist.normalBuffer = createBuffer(context,norm,3,context.STATIC_DRAW); - plist.tex0Buffer = createBuffer(context,t0,2,context.STATIC_DRAW); - plist.tex1Buffer = createBuffer(context,t1,2,context.STATIC_DRAW); - plist.tex2Buffer = createBuffer(context,t2,2,context.STATIC_DRAW); - plist.colorBuffer = createBuffer(context,col,4,context.STATIC_DRAW); - plist.tangentBuffer = createBuffer(context,tan,3,context.STATIC_DRAW); - - if (index.length>0 && s_uintElements) { - plist.indexBuffer = context.createBuffer(); - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint32Array(index),context.STATIC_DRAW); - plist.indexBuffer.itemSize = 3; - plist.indexBuffer.numItems = index.length; - } - else { - plist.indexBuffer = context.createBuffer(); - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint16Array(index),context.STATIC_DRAW); - plist.indexBuffer.itemSize = 3; - plist.indexBuffer.numItems = index.length; - } - - return plist.vertexBuffer && plist.indexBuffer; - } - - draw(context,plist,drawMode,numberOfIndex) { - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - if (s_uintElements) { - context.drawElements(drawMode, numberOfIndex, context.UNSIGNED_INT, 0); - } - else { - context.drawElements(drawMode, numberOfIndex, context.UNSIGNED_SHORT, 0); - } - } - - destroy(context,plist) { - context.bindBuffer(context.ARRAY_BUFFER, null); - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, null); - - plist.vertexBuffer = deleteBuffer(context,plist.vertexBuffer); - plist.normalBuffer = deleteBuffer(context,plist.normalBuffer); - plist.tex0Buffer = deleteBuffer(context,plist.tex0Buffer); - plist.tex1Buffer = deleteBuffer(context,plist.tex1Buffer); - plist.tex2Buffer = deleteBuffer(context,plist.tex2Buffer); - plist.colorBuffer = deleteBuffer(context,plist.colorBuffer); - plist.tangentBuffer = deleteBuffer(context,plist.tangentBuffer); - plist.indexBuffer = deleteBuffer(context,plist.indexBuffer); - } - - update(context,plist,bufferType,newData) { - if (bufferType==bg.base.BufferType.INDEX) { - if (s_uintElements) { - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint32Array(index),context.STATIC_DRAW); - } - else { - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, plist.indexBuffer); - context.bufferData(context.ELEMENT_ARRAY_BUFFER, new Uint16Array(index),context.STATIC_DRAW); - } - context.bindBuffer(context.ELEMENT_ARRAY_BUFFER,null); - } - else { - switch (bufferType) { - case bg.base.BufferType.VERTEX: - context.bindBuffer(context.ARRAY_BUFFER, plist.vertexBuffer); - break; - case bg.base.BufferType.NORMAL: - context.bindBuffer(context.ARRAY_BUFFER, plist.normalBuffer); - break; - case bg.base.BufferType.TEX_COORD_0: - context.bindBuffer(context.ARRAY_BUFFER, plist.tex0Buffer); - break; - case bg.base.BufferType.TEX_COORD_1: - context.bindBuffer(context.ARRAY_BUFFER, plist.tex1Buffer); - break; - case bg.base.BufferType.TEX_COORD_2: - context.bindBuffer(context.ARRAY_BUFFER, plist.tex2Buffer); - break; - case bg.base.BufferType.COLOR: - context.bindBuffer(context.ARRAY_BUFFER, plist.colorBuffer); - break; - case bg.base.BufferType.TANGENT: - context.bindBuffer(context.ARRAY_BUFFER, plist.tangentBuffer); - break; - } - context.bufferData(context.ARRAY_BUFFER, new Float32Array(newData), context.STATIC_DRAW); - context.bindBuffer(context.ARRAY_BUFFER,null); - } - } - } - - bg.webgl1.PolyListImpl = PolyListImpl; -})(); - -(function() { - - let ext = null; - - function getMaxColorAttachments() { - if (ext.drawBuffers) { - return ext.drawBuffers.MAX_COLOR_ATTACHMENTS || - ext.drawBuffers.MAX_COLOR_ATTACHMENTS_WEBGL; - } - return 1; - } - - // type: RGBA, format: UNSIGNED_BYTE => regular RGBA texture - // type: RGBA, format: FLOAT => float texture attachment - // type: DEPTH, format: RENDERBUFFER => regular depth renderbuffer - // type: DEPTH, format: UNSIGNED_SHORT => depth texture - // every one else: error, unsupported combination - function checkValid(attachment) { - switch (true) { - case attachment.type==bg.base.RenderSurfaceType.RGBA && attachment.format==bg.base.RenderSurfaceFormat.UNSIGNED_BYTE: - return true; - case attachment.type==bg.base.RenderSurfaceType.RGBA && attachment.format==bg.base.RenderSurfaceFormat.FLOAT: - return true; - case attachment.type==bg.base.RenderSurfaceType.DEPTH && attachment.format==bg.base.RenderSurfaceFormat.RENDERBUFFER: - return true; - case attachment.type==bg.base.RenderSurfaceType.DEPTH && attachment.format==bg.base.RenderSurfaceFormat.UNSIGNED_SHORT: - return true; - // TODO: Cubemaps - default: - return false; - } - } - - function getTypeString(type) { - switch (type) { - case bg.base.RenderSurfaceType.RGBA: - return "RGBA"; - case bg.base.RenderSurfaceType.DEPTH: - return "DEPTH"; - default: - return "unknown"; - } - } - - function getFormatString(format) { - switch (format) { - case bg.base.RenderSurfaceFormat.UNSIGNED_BYTE: - return "UNSIGNED_BYTE"; - case bg.base.RenderSurfaceFormat.FLOAT: - return "FLOAT"; - case bg.base.RenderSurfaceFormat.RENDERBUFFER: - return "RENDERBUFFER"; - case bg.base.RenderSurfaceFormat.UNSIGNED_SHORT: - return "UNSIGNED_SHORT"; - default: - return "unknown"; - } - } - - function checkCompatibility(attachments) { - let colorAttachments = 0; - let maxColorAttachments = getMaxColorAttachments(); - let error = null; - - attachments.every(function(att,index) { - if (!checkValid(att)) { - error = `Error in attachment ${index}: Invalid combination of type and format (${getTypeString(att.type)} is incompatible with ${getFormatString(att.format)}).`; - return false; - } - - if (att.type==bg.base.RenderSurfaceType.DEPTH && - index!=attachments.length-1 - ) { - error = `Error in attachment ${index}: Depth attachment must be specified as the last attachment. Specified at index ${index} of ${attachments.length - 1}`; - return false; - } - - if (att.type==bg.base.RenderSurfaceType.RGBA) { - ++colorAttachments; - } - - if (att.format==bg.base.RenderSurfaceFormat.FLOAT && !ext.textureFloat) { - error = `Error in attachment ${index}: Floating point render surface requested, but the required extension is not present: OES_texture_float.`; - return false; - } - if (att.type==bg.base.RenderSurfaceType.DEPTH && - att.format!=bg.base.RenderSurfaceFormat.RENDERBUFFER && - !ext.depthTexture - ) { - error = `Error in attachment ${index}: Depth texture attachment requested, but the requiered extension is not present: WEBGL_depth_texture.`; - return false; - } - if (colorAttachments>maxColorAttachments) { - error = `Error in attachment ${index}: Maximum number of ${maxColorAttachments} color attachment exceeded.`; - return false; - } - - return true; - }); - - return error; - } - - function addAttachment(gl,size,attachment,index) { - if (attachment.format==bg.base.RenderSurfaceFormat.RENDERBUFFER) { - let renderbuffer = gl.createRenderbuffer(); - - gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); - gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,size.width,size.height); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer); - gl.bindRenderbuffer(gl.RENDERBUFFER,null); - - return { _renderbuffer: renderbuffer }; - } - else { - let texture = new bg.base.Texture(gl); - let format = attachment.format; - let type = attachment.type; - - texture.create(); - texture.bind(); - texture.minFilter = bg.base.TextureFilter.LINEAR; - texture.magFilter = bg.base.TextureFilter.LINEAR; - texture.wrapX = bg.base.TextureWrap.CLAMP; - texture.wrapY = bg.base.TextureWrap.CLAMP; - texture.setImageRaw(size.width,size.height,null,type,format); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + index, gl.TEXTURE_2D, texture._texture, 0); - texture.unbind(); - - return texture; - } - } - - function resizeAttachment(gl,size,att,index) { - if (att.texture) { - att.texture.bind(); - att.texture.setImageRaw(size.width,size.height,null,att.type,att.format); - att.texture.unbind(); - } - if (att.renderbuffer) { - let rb = att.renderbuffer._renderbuffer; - gl.bindRenderbuffer(gl.RENDERBUFFER,rb); - gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16, size.width, size.height); - gl.bindRenderbuffer(gl.RENDERBUFFER,null); - } - } - - - class WebGLRenderSurfaceImpl extends bg.base.RenderSurfaceBufferImpl { - initFlags(gl) { - bg.base.RenderSurfaceType.RGBA = gl.RGBA; - bg.base.RenderSurfaceType.DEPTH = gl.DEPTH_COMPONENT; - - bg.base.RenderSurfaceFormat.UNSIGNED_BYTE = gl.UNSIGNED_BYTE; - bg.base.RenderSurfaceFormat.UNSIGNED_SHORT = gl.UNSIGNED_SHORT; - bg.base.RenderSurfaceFormat.FLOAT = gl.FLOAT; - // This is not a format. This will create a renderbuffer instead a texture - bg.base.RenderSurfaceFormat.RENDERBUFFER = gl.RENDERBUFFER; - - ext = bg.webgl1.Extensions.Get(); - } - - supportType(type) { - switch (type) { - case bg.base.RenderSurfaceType.RGBA: - return true; - case bg.base.RenderSurfaceType.DEPTH: - return ext.depthTexture!=null; - default: - return false; - } - } - - supportFormat(format) { - switch (format) { - case bg.base.RenderSurfaceFormat.UNSIGNED_BYTE: - case bg.base.RenderSurfaceFormat.UNSIGNED_SHORT: - return true; - case bg.base.RenderSurfaceFormat.FLOAT: - return ext.textureFloat!=null; - default: - return false; - } - } - - get maxColorAttachments() { - return getMaxColorAttachments(); - } - } - - class ColorRenderSurfaceImpl extends WebGLRenderSurfaceImpl { - create(gl) { - return {}; - } - setActive(gl,renderSurface,attachments) { - gl.bindFramebuffer(gl.FRAMEBUFFER,null); - } - resize(gl,renderSurface,size) {} - destroy(gl,renderSurface) {} - - readBuffer(gl,renderSurface,rectangle,viewportSize) { - let pixels = new Uint8Array(rectangle.width * rectangle.height * 4); - // Note that the webgl texture is flipped vertically, so we need to convert the Y coord - gl.readPixels(rectangle.x, rectangle.y, rectangle.width, rectangle.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); - return pixels; - } - } - - bg.webgl1.ColorRenderSurfaceImpl = ColorRenderSurfaceImpl; - - class TextureRenderSurfaceImpl extends WebGLRenderSurfaceImpl { - initFlags(gl) {} // Flags initialized in ColorRenderSurfaceImpl - - create(gl,attachments) { - // If this function returns no error, the browser is compatible with - // the specified attachments. - let error = checkCompatibility(attachments); - if (error) { - throw new Error(error); - } - // Initial size of 256. The actual size will be defined in resize() function - let size = new bg.Vector2(256); - let surfaceData = { - fbo: gl.createFramebuffer(), - size: size, - attachments: [] - }; - - gl.bindFramebuffer(gl.FRAMEBUFFER, surfaceData.fbo); - - let colorAttachments = []; - attachments.forEach((att,i) => { - // This will return a bg.base.Texture or a renderbuffer - let result = addAttachment(gl,size,att,i); - if (result instanceof bg.base.Texture) { - colorAttachments.push(ext.drawBuffers ? ext.drawBuffers.COLOR_ATTACHMENT0_WEBGL + i : gl.COLOR_ATTACHMENT0); - } - surfaceData.attachments.push({ - texture: result instanceof bg.base.Texture ? result:null, - renderbuffer: result instanceof bg.base.Texture ? null:result, - format:att.format, - type:att.type - }); - }); - if (colorAttachments.length>1) { - ext.drawBuffers.drawBuffersWEBGL(colorAttachments); - } - - gl.bindFramebuffer(gl.FRAMEBUFFER,null); - return surfaceData; - } - - setActive(gl,renderSurface) { - gl.bindFramebuffer(gl.FRAMEBUFFER,renderSurface.fbo); - } - - readBuffer(gl,renderSurface,rectangle,viewportSize) { - let pixels = new Uint8Array(rectangle.width * rectangle.height * 4); - // Note that the webgl texture is flipped vertically, so we need to convert the Y coord - gl.readPixels(rectangle.x, viewportSize.height - rectangle.y, rectangle.width, rectangle.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); - return pixels; - } - - resize(gl,renderSurface,size) { - renderSurface.size.width = size.width; - renderSurface.size.height = size.height; - renderSurface.attachments.forEach((att,index) => { - resizeAttachment(gl,size,att,index); - }); - } - - destroy(gl,renderSurface) { - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - let attachments = renderSurface && renderSurface.attachments; - if (renderSurface.fbo) { - gl.deleteFramebuffer(renderSurface.fbo); - } - if (attachments) { - attachments.forEach((attachment) => { - if (attachment.texture) { - attachment.texture.destroy(); - } - else if (attachment.renderbuffer) { - gl.deleteRenderbuffer(attachment.renderbuffer._renderbuffer); - } - }); - } - renderSurface.fbo = null; - renderSurface.size = null; - renderSurface.attachments = null; - } - } - - bg.webgl1.TextureRenderSurfaceImpl = TextureRenderSurfaceImpl; -})(); -(function() { - let MAX_BLUR_ITERATIONS = 40; - - let BLUR_DOWNSAMPLE = 15 ; - - let textureCubeDownsampleParams = { - textureInput:'samplerCube', texCoord:'vec3', size:'vec2', reduction:'vec2' - }; - let textureCubeDownsampleBody = ` - float dx = reduction.x / size.x; - float dy = reduction.y / size.y; - vec2 coord = vec2(dx * texCoord.x / dx, dy * texCoord.y / dy); - return textureCube(textureInput,coord); - `; - - let textureDownsampleParams = { - textureInput:'sampler2D', texCoord:'vec2', size:'vec2', reduction:'vec2' - }; - let textureDownsampleBody = ` - float dx = reduction.x / size.x; - float dy = reduction.y / size.y; - vec2 coord = vec2(dx * texCoord.x / dx, dy * texCoord.y / dy); - return texture2D(textureInput,coord); - `; - - let blurParams = { - textureInput:'sampler2D', texCoord:'vec2', size:'int', samplerSize:'vec2' - }; - let blurBody = ` - int downsample = ${ BLUR_DOWNSAMPLE }; - vec2 texelSize = 1.0 / samplerSize; - vec3 result = vec3(0.0); - size = int(max(float(size / downsample),1.0)); - vec2 hlim = vec2(float(-size) * 0.5 + 0.5); - vec2 sign = vec2(1.0); - float blurFactor = 10.0 - 0.2 * float(size) * log(float(size)); - for (int x=0; x<${ MAX_BLUR_ITERATIONS }; ++x) { - if (x==size) break; - for (int y=0; y<${ MAX_BLUR_ITERATIONS }; ++y) { - if (y==size) break; - vec2 offset = (hlim + vec2(float(x), float(y))) * texelSize * float(downsample) / blurFactor; - result += textureDownsample(textureInput, texCoord + offset,samplerSize,vec2(downsample)).rgb; - } - } - return vec4(result / float(size * size), 1.0); - `; - - let glowParams = { - textureInput:'sampler2D', texCoord:'vec2', size:'int', samplerSize:'vec2' - }; - let glowBody = ` - int downsample = ${ BLUR_DOWNSAMPLE }; - vec2 texelSize = 1.0 / samplerSize; - vec3 result = vec3(0.0); - size = int(max(float(size / downsample),1.0)); - vec2 hlim = vec2(float(-size) * 0.5 + 0.5); - vec2 sign = vec2(1.0); - for (int x=0; x<${ MAX_BLUR_ITERATIONS }; ++x) { - if (x==size) break; - for (int y=0; y<${ MAX_BLUR_ITERATIONS }; ++y) { - if (y==size) break; - vec2 offset = (hlim + vec2(float(x), float(y))) * texelSize; - result += textureDownsample(textureInput, texCoord + offset,samplerSize,vec2(downsample)).rgb; - } - } - return vec4(result / float(size * size), 1.0); - `; - - let blurCubeParams = { - textureInput:'samplerCube', texCoord:'vec3', size:'int', samplerSize:'vec2', dist:'float' - }; - let blurCubeBody = ` - int downsample = int(max(1.0,dist)); - vec2 texelSize = 1.0 / samplerSize; - vec3 result = vec3(0.0); - size = int(max(float(size / downsample),1.0)); - vec2 hlim = vec2(float(-size) * 0.5 + 0.5); - vec2 sign = vec2(1.0); - for (int x=0; x<40; ++x) { - if (x==size) break; - for (int y=0; y<40; ++y) { - if (y==size) break; - vec3 offset = vec3((hlim + vec2(float(x*downsample), float(y*downsample))) * texelSize,0.0); - result += textureCube(textureInput, texCoord + offset,2.0).rgb; - } - } - return vec4(result / float(size * size), 1.0); - `; - - bg.webgl1.shaderLibrary - .functions - .blur = { - textureDownsample:{ - returnType:"vec4", name:'textureDownsample', params:textureDownsampleParams, body:textureDownsampleBody - }, - gaussianBlur:{ - returnType:"vec4", name:"gaussianBlur", params:blurParams, body:blurBody - }, - blur:{ - returnType:"vec4", name:"blur", params:blurParams, body:blurBody - }, - glowBlur:{ - returnType:"vec4", name:"glowBlur", params:glowParams, body:glowBody - }, - blurCube:{ - returnType:"vec4", name:"blurCube", params:blurCubeParams, body:blurCubeBody - }, - - // Require: utils.borderDetection - antiAlias:{ - returnType:'vec4', name:'antiAlias', params: { - sampler:'sampler2D', texCoord:'vec2', frameSize:'vec2', tresshold:'float', iterations:'int' - }, body: ` - return (borderDetection(sampler,texCoord,frameSize)>tresshold) ? - gaussianBlur(sampler,texCoord,iterations,frameSize) : - texture2D(sampler,texCoord); - ` - } - } -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .colorCorrection = { - rgb2hsv: { - returnType:"vec3", name:"rgb2hsv", params:{ c:"vec3" }, body:` - vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); - vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); - - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);` - }, - hsv2rgb: { - returnType:"vec3", name:"hsv2rgb", params: { c:"vec3" }, body:` - vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); - return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);` - }, - applyBrightness: { - returnType:"vec4", name:"applyBrightness", params: { color:"vec4", brightness:"float" }, body:` - return clamp(vec4(color.rgb + brightness - 0.5,1.0),0.0,1.0); - ` - }, - applyContrast: { - returnType:"vec4", name:"applyContrast", params:{ color:"vec4", contrast:"float" }, body:` - return clamp(vec4((color.rgb * max(contrast + 0.5,0.0)),1.0),0.0,1.0);` - }, - applySaturation: { - returnType:"vec4", name:"applySaturation", params:{ color:"vec4", hue:"float", saturation:"float", lightness:"float" }, body:` - vec3 fragRGB = clamp(color.rgb + vec3(0.001),0.0,1.0); - vec3 fragHSV = rgb2hsv(fragRGB); - lightness -= 0.01; - float h = hue; - fragHSV.x *= h; - fragHSV.yz *= vec2(saturation,lightness); - fragHSV.x = mod(fragHSV.x, 1.0); - fragHSV.y = mod(fragHSV.y, 1.0); - fragHSV.z = mod(fragHSV.z, 1.0); - fragRGB = hsv2rgb(fragHSV); - return clamp(vec4(hsv2rgb(fragHSV), color.w),0.0,1.0);` - }, - colorCorrection: { - returnType:"vec4", name:"colorCorrection", params:{ - fragColor:"vec4", hue:"float", saturation:"float", - lightness:"float", brightness:"float", contrast:"float" }, - body:` - return applyContrast(applyBrightness(applySaturation(fragColor,hue,saturation,lightness),brightness),contrast);` - } - } - -})(); -(function() { - - bg.webgl1.shaderLibrary - .inputs = { - // Input buffers - buffers: { - vertex: { name:"inVertex", dataType:"vec3", role:"buffer", target:"vertex" }, // role:buffer => attribute - normal: { name:"inNormal", dataType:"vec3", role:"buffer", target:"normal" }, - tangent: { name:"inTangent", dataType:"vec3", role:"buffer", target:"tangent" }, - tex0: { name:"inTex0", dataType:"vec2", role:"buffer", target:"tex0" }, - tex1: { name:"inTex1", dataType:"vec2", role:"buffer", target:"tex1" }, - tex2: { name:"inTex2", dataType:"vec2", role:"buffer", target:"tex2" }, - color: { name:"inColor", dataType:"vec4", role:"buffer", target:"color" } - }, - - // Matrixes - matrix: { - model: { name:"inModelMatrix", dataType:"mat4", role:"value" }, // role:value => uniform - view: { name:"inViewMatrix", dataType:"mat4", role:"value" }, - projection: { name:"inProjectionMatrix", dataType:"mat4", role:"value" }, - normal: { name:"inNormalMatrix", dataType:"mat4", role:"value" }, - viewInv: { name:"inViewMatrixInv", dataType:"mat4", role:"value" } - }, - - ///// Material properties - material: { - // Color - diffuse: { name:"inDiffuseColor", dataType:"vec4", role:"value" }, - specular: { name:"inSpecularColor", dataType:"vec4", role:"value" }, - - // Shininess - shininess: { name:"inShininess", dataType:"float", role:"value" }, - shininessMask: { name:"inShininessMask", dataType:"sampler2D", role:"value" }, - shininessMaskChannel: { name:"inShininessMaskChannel", dataType:"vec4", role:"value" }, - shininessMaskInvert: { name:"inShininessMaskInvert", dataType:"bool", role:"value" }, - - // Light emission - lightEmission: { name:"inLightEmission", dataType:"float", role:"value" }, - lightEmissionMask: { name:"inLightEmissionMask", dataType:"sampler2D", role:"value" }, - lightEmissionMaskChannel: { name:"inLightEmissionMaskChannel", dataType:"vec4", role:"value" }, - lightEmissionMaskInvert: { name:"inLightEmissionMaskInvert", dataType:"bool", role:"value" }, - - - // Textures - texture: { name:"inTexture", dataType:"sampler2D", role:"value" }, - textureOffset: { name:"inTextureOffset", dataType:"vec2", role:"value" }, - textureScale: { name:"inTextureScale", dataType:"vec2", role:"value" }, - alphaCutoff: { name:"inAlphaCutoff", dataType:"float", role:"value" }, - - lightMap: { name:"inLightMap", dataType:"sampler2D", role:"value" }, - lightMapOffset: { name:"inLightMapOffset", dataType:"vec2", role:"value" }, - lightMapScale: { name:"inLightMapScale", dataType:"vec2", role:"value" }, - - normalMap: { name:"inNormalMap", dataType:"sampler2D", role:"value" }, - normalMapOffset: { name:"inNormalMapOffset", dataType:"vec2", role:"value" }, - normalMapScale: { name:"inNormalMapScale", dataType:"vec2", role:"value" }, - - // Reflection - reflection: { name:"inReflection", dataType:"float", role:"value" }, - reflectionMask: { name:"inReflectionMask", dataType:"sampler2D", role:"value" }, - reflectionMaskChannel: { name:"inReflectionMaskChannel", dataType:"vec4", role:"value" }, - reflectionMaskInvert: { name:"inReflectionMaskInvert", dataType:"bool", role:"value" }, - - // Shadows - castShadows: { name:"inCastShadows", dataType:"bool", role:"value" }, - receiveShadows: { name:"inReceiveShadows", dataType:"bool", role:"value" }, - - // Roughness - roughness: { name:"inRoughness", dataType:"float", role:"value" }, - roughnessMask: { name:"inRoughnessMask", dataType:"sampler2D", role:"value" }, - roughnessMaskChannel: { name:"inRoughnessMaskChannel", dataType:"vec4", role:"value" }, - roughnessMaskInvert: { name:"inRoughnessMaskInvert", dataType:"bool", role:"value" }, - - unlit: { name:"inUnlit", dataType:"bool", role:"value" } - }, - - // Lighting - lighting: { - type: { name:"inLightType", dataType:"int", role:"value" }, - position: { name:"inLightPosition", dataType:"vec3", role:"value" }, - direction: { name:"inLightDirection", dataType:"vec3", role:"value" }, - ambient: { name:"inLightAmbient", dataType:"vec4", role:"value" }, - diffuse: { name:"inLightDiffuse", dataType:"vec4", role:"value" }, - specular: { name:"inLightSpecular", dataType:"vec4", role:"value" }, - attenuation: { name:"inLightAttenuation", dataType:"vec3", role:"value" }, // const, linear, exp - spotExponent: { name:"inSpotExponent", dataType:"float", role:"value" }, - spotCutoff: { name:"inSpotCutoff", dataType:"float", role:"value" }, - cutoffDistance: { name:"inLightCutoffDistance", dataType:"float", role:"value" }, - exposure: { name:"inLightExposure", dataType:"float", role:"value" }, - castShadows: { name:"inLightCastShadows", dataType:"bool", role:"value" } - }, - - lightingForward: { - type: { name:"inLightType", dataType:"int", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - position: { name:"inLightPosition", dataType:"vec3", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - direction: { name:"inLightDirection", dataType:"vec3", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - ambient: { name:"inLightAmbient", dataType:"vec4", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - diffuse: { name:"inLightDiffuse", dataType:"vec4", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - specular: { name:"inLightSpecular", dataType:"vec4", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - attenuation: { name:"inLightAttenuation", dataType:"vec3", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, // const, linear, exp - spotExponent: { name:"inSpotExponent", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - spotCutoff: { name:"inSpotCutoff", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - cutoffDistance: { name:"inLightCutoffDistance", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - exposure: { name:"inLightExposure", dataType:"float", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - castShadows: { name:"inLightCastShadows", dataType:"bool", role:"value", vec:bg.base.MAX_FORWARD_LIGHTS }, - numLights: { name:"inNumLights", dataType:"int", role:"value" } - }, - - // Shadows - shadows: { - shadowMap: { name:"inShadowMap", dataType:"sampler2D", role:"value" }, - shadowMapSize: { name:"inShadowMapSize", dataType:"vec2", role:"value" }, - shadowStrength: { name:"inShadowStrength", dataType:"float", role:"value" }, - shadowColor: { name:"inShadowColor", dataType:"vec4", role:"value" }, - shadowBias: { name:"inShadowBias", dataType:"float", role:"value" }, - shadowType: { name:"inShadowType", dataType:"int", role:"value" } - }, - - // Color correction - colorCorrection: { - hue: { name:"inHue", dataType:"float", role:"value" }, - saturation: { name:"inSaturation", dataType:"float", role:"value" }, - lightness: { name:"inLightness", dataType:"float", role:"value" }, - brightness: { name:"inBrightness", dataType:"float", role:"value" }, - contrast: { name:"inContrast", dataType:"float", role:"value" } - } - - } -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .lighting = { - beckmannDistribution: { - returnType:"float", name:"beckmannDistribution", params: { - x:"float", roughness:"float" - }, body: ` - float NdotH = max(x,0.0001); - float cos2Alpha = NdotH * NdotH; - float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha; - float roughness2 = roughness * roughness; - float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha; - return exp(tan2Alpha / roughness2) / denom; - ` - }, - - beckmannSpecular: { - returnType:"float", name:"beckmannSpecular", params:{ - lightDirection:"vec3", viewDirection:"vec3", surfaceNormal:"vec3", roughness:"float" - }, body: ` - return beckmannDistribution(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness); - ` - }, - - getDirectionalLight: { - returnType:"vec4", name:"getDirectionalLight", params:{ - ambient:"vec4", diffuse:"vec4", specular:"vec4", shininess:"float", - direction:"vec3", vertexPos:"vec3", normal:"vec3", matDiffuse:"vec4", matSpecular:"vec4", - shadowColor:"vec4", - specularOut:"out vec4" - }, body: ` - vec3 color = ambient.rgb * matDiffuse.rgb; - vec3 diffuseWeight = max(0.0, dot(normal,direction)) * diffuse.rgb; - color += min(diffuseWeight,shadowColor.rgb) * matDiffuse.rgb; - specularOut = vec4(0.0,0.0,0.0,1.0); - if (shininess>0.0) { - vec3 eyeDirection = normalize(-vertexPos); - vec3 reflectionDirection = normalize(reflect(-direction,normal)); - float specularWeight = clamp(pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess), 0.0, 1.0); - //sspecularWeight = beckmannSpecular(direction,eyeDirection,normal,0.01); - vec3 specularColor = specularWeight * pow(shadowColor.rgb,vec3(10.0)); - //color += specularColor * specular.rgb * matSpecular.rgb; - specularOut = vec4(specularColor * specular.rgb * matSpecular.rgb,1.0); - } - return vec4(color,1.0);` - }, - - getPointLight: { - returnType:"vec4", name:"getPointLight", params: { - ambient: "vec4", diffuse: "vec4", specular: "vec4", shininess: "float", - position: "vec3", constAtt: "float", linearAtt: "float", expAtt: "float", - vertexPos: "vec3", normal: "vec3", matDiffuse: "vec4", matSpecular: "vec4", - specularOut:"out vec4" - }, body: ` - vec3 pointToLight = position - vertexPos; - float distance = length(pointToLight); - vec3 lightDir = normalize(pointToLight); - float attenuation = 1.0 / (constAtt + linearAtt * distance + expAtt * distance * distance); - vec3 color = ambient.rgb * matDiffuse.rgb; - vec3 diffuseWeight = max(0.0,dot(normal,lightDir)) * diffuse.rgb * attenuation; - color += diffuseWeight * matDiffuse.rgb; - specularOut = vec4(0.0,0.0,0.0,1.0); - if (shininess>0.0) { - vec3 eyeDirection = normalize(-vertexPos); - vec3 reflectionDirection = normalize(reflect(-lightDir, normal)); - float specularWeight = clamp(pow(max(dot(reflectionDirection,eyeDirection),0.0), shininess), 0.0, 1.0); - //color += specularWeight * specular.rgb * matSpecular.rgb * attenuation; - specularOut = vec4(specularWeight * specular.rgb * matSpecular.rgb * attenuation,1.0); - } - return vec4(color,1.0);` - }, - - getSpotLight: { - returnType:"vec4", name:"getSpotLight", params: { - ambient:"vec4", diffuse:"vec4", specular:"vec4", shininess:"float", - position:"vec3", direction:"vec3", - constAtt:"float", linearAtt:"float", expAtt:"float", - spotCutoff:"float", spotExponent:"float", - vertexPos:"vec3", normal:"vec3", - matDiffuse:"vec4", matSpecular:"vec4", shadowColor:"vec4", - specularOut:"out vec4" - }, body: ` - vec4 matAmbient = vec4(1.0); - vec3 s = normalize(position - vertexPos); - float angle = acos(dot(-s, direction)); - float cutoff = radians(clamp(spotCutoff / 2.0,0.0,90.0)); - float distance = length(position - vertexPos); - float attenuation = 1.0 / (constAtt );//+ linearAtt * distance + expAtt * distance * distance); - if (angle0.0) { - specularOut.rgb = matSpecular.rgb * specular.rgb * pow(max(dot(h,normal), 0.0),shininess); - specularOut.rgb *= pow(shadowColor.rgb,vec3(10.0)); - //diffuseAmount += matSpecular.rgb * specular.rgb * pow(max(dot(h,normal), 0.0),shininess); - //diffuseAmount *= pow(shadowColor.rgb,vec3(10.0)); - } - diffuseAmount.r = min(diffuseAmount.r, shadowColor.r); - diffuseAmount.g = min(diffuseAmount.g, shadowColor.g); - diffuseAmount.b = min(diffuseAmount.b, shadowColor.b); - return vec4(ambient.rgb * matDiffuse.rgb + attenuation * spotFactor * diffuseAmount,1.0); - } - else { - return vec4(ambient.rgb * matDiffuse.rgb,1.0); - }` - }, - - getLight: { - returnType:"vec4", name:"getLight", params: { - lightType:"int", - ambient:"vec4", diffuse:"vec4", specular:"vec4", shininess:"float", - lightPosition:"vec3", lightDirection:"vec3", - constAtt:"float", linearAtt:"float", expAtt:"float", - spotCutoff:"float", spotExponent:"float",cutoffDistance:"float", - vertexPosition:"vec3", vertexNormal:"vec3", - matDiffuse:"vec4", matSpecular:"vec4", shadowColor:"vec4", - specularOut:"out vec4" - }, body: ` - vec4 light = vec4(0.0); - if (lightType==${ bg.base.LightType.DIRECTIONAL }) { - light = getDirectionalLight(ambient,diffuse,specular,shininess, - -lightDirection,vertexPosition,vertexNormal,matDiffuse,matSpecular,shadowColor,specularOut); - } - else if (lightType==${ bg.base.LightType.SPOT }) { - float d = distance(vertexPosition,lightPosition); - if (d<=cutoffDistance || cutoffDistance==-1.0) { - light = getSpotLight(ambient,diffuse,specular,shininess, - lightPosition,lightDirection, - constAtt,linearAtt,expAtt, - spotCutoff,spotExponent, - vertexPosition,vertexNormal,matDiffuse,matSpecular,shadowColor,specularOut); - } - } - else if (lightType==${ bg.base.LightType.POINT }) { - float d = distance(vertexPosition,lightPosition); - if (d<=cutoffDistance || cutoffDistance==-1.0) { - light = getPointLight(ambient,diffuse,specular,shininess, - lightPosition, - constAtt,linearAtt,expAtt, - vertexPosition,vertexNormal,matDiffuse,matSpecular,specularOut); - } - } - return light; - ` - }, - - getShadowColor:{ - returnType:"vec4", name:"getShadowColor", params:{ - vertexPosFromLight:'vec4', shadowMap:'sampler2D', shadowMapSize:'vec2', - shadowType:'int', shadowStrength:'float', shadowBias:'float', shadowColor:'vec4' - }, body:` - float visibility = 1.0; - vec3 depth = vertexPosFromLight.xyz / vertexPosFromLight.w; - const float kShadowBorderOffset = 3.0; - float shadowBorderOffset = kShadowBorderOffset / shadowMapSize.x; - float bias = shadowBias; - vec4 shadow = vec4(1.0); - if (shadowType==${ bg.base.ShadowType.HARD }) { // hard - float shadowDepth = unpack(texture2D(shadowMap,depth.xy)); - if (shadowDepth0.0 && depth.x<1.0 && depth.y>0.0 && depth.y<1.0)) - { - visibility = 1.0 - shadowStrength; - } - shadow = clamp(shadowColor + visibility,0.0,1.0); - } - else if (shadowType>=${ bg.base.ShadowType.SOFT }) { // soft / soft stratified (not supported on webgl, fallback to soft) - vec2 poissonDisk[4]; - poissonDisk[0] = vec2( -0.94201624, -0.39906216 ); - poissonDisk[1] = vec2( 0.94558609, -0.76890725 ); - poissonDisk[2] = vec2( -0.094184101, -0.92938870 ); - poissonDisk[3] = vec2( 0.34495938, 0.29387760 ); - - for (int i=0; i<4; ++i) { - float shadowDepth = unpack(texture2D(shadowMap, depth.xy + poissonDisk[i]/1000.0)); - - if (shadowDepth0.0 && depth.x<1.0 && depth.y>0.0 && depth.y<1.0)) { - visibility -= (shadowStrength) * 0.25; - } - } - shadow = clamp(shadowColor + visibility,0.0,1.0); - } - return shadow;` - } - } -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .materials = { - samplerColor: { - returnType:"vec4", name:"samplerColor", params: { - sampler:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2" - }, body:` - return texture2D(sampler,uv * scale + offset);` - }, - - samplerNormal: { - returnType:"vec3", name:"samplerNormal", params:{ - sampler:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2" - }, body:` - return normalize(samplerColor(sampler,uv,offset,scale).xyz * 2.0 - 1.0); - ` - }, - - combineNormalWithMap:{ - returnType:"vec3", name:"combineNormalWithMap", params:{ - normalCoord:"vec3", - tangent:"vec3", - bitangent:"vec3", - normalMapValue:"vec3" - }, body:` - mat3 tbnMat = mat3( tangent.x, bitangent.x, normalCoord.x, - tangent.y, bitangent.y, normalCoord.y, - tangent.z, bitangent.z, normalCoord.z - ); - return normalize(normalMapValue * tbnMat);` - }, - - applyTextureMask:{ - returnType:"float", name:"applyTextureMask", params: { - value:"float", - textureMask:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2", - channelMask:"vec4", - invert:"bool" - }, body:` - float mask; - vec4 color = samplerColor(textureMask,uv,offset,scale); - mask = color.r * channelMask.r + - color.g * channelMask.g + - color.b * channelMask.b + - color.a * channelMask.a; - if (invert) { - mask = 1.0 - mask; - } - return value * mask;` - }, - - specularColor:{ - returnType:"vec4", name:"specularColor", params:{ - specular:"vec4", - shininessMask:"sampler2D", - uv:"vec2", offset:"vec2", scale:"vec2", - channelMask:"vec4", - invert:"bool" - }, body:` - float maskValue = applyTextureMask(1.0, shininessMask,uv,offset,scale,channelMask,invert); - return vec4(specular.rgb * maskValue, 1.0);` - } - }; - -})(); -(function() { - - bg.webgl1.shaderLibrary - .functions - .utils = { - pack: { - returnType:"vec4", name:"pack", params:{ depth:"float" }, body: ` - const vec4 bitSh = vec4(256 * 256 * 256, - 256 * 256, - 256, - 1.0); - const vec4 bitMsk = vec4(0, - 1.0 / 256.0, - 1.0 / 256.0, - 1.0 / 256.0); - vec4 comp = fract(depth * bitSh); - comp -= comp.xxyz * bitMsk; - return comp;` - }, - - unpack: { - returnType:"float", name:"unpack", params:{ color:"vec4" }, body:` - const vec4 bitShifts = vec4(1.0 / (256.0 * 256.0 * 256.0), - 1.0 / (256.0 * 256.0), - 1.0 / 256.0, - 1.0); - return dot(color, bitShifts);` - }, - - random: { - returnType:"float", name:"random", params:{ - seed:"vec3", i:"int" - }, body:` - vec4 seed4 = vec4(seed,i); - float dot_product = dot(seed4, vec4(12.9898,78.233,45.164,94.673)); - return fract(sin(dot_product) * 43758.5453);` - }, - - texOffset: { - returnType: 'vec4', name:'texOffset', params: { - sampler:'sampler2D', - texCoord:'vec2', - offset:'vec2', - frameSize:'vec2' - }, body: ` - return texture2D(sampler,texCoord + vec2(offset.x * 1.0/frameSize.x,offset.y * 1.0 / frameSize.y)); - ` - }, - - luminance: { - returnType: 'float', name:'luminance', params: { color:'vec3' }, body: ` - return dot(vec3(0.2126,0.7152,0.0722), color); - ` - }, - - // Require: colorCorrection.luminance and utils.texOffset - borderDetection:{ - returnType: 'float', name:'borderDetection', params: { - sampler:'sampler2D', texCoord:'vec2', frameSize:'vec2' - }, body: ` - float s00 = luminance(texOffset(sampler,texCoord,vec2(-1.0, 1.0),frameSize).rgb); - float s10 = luminance(texOffset(sampler,texCoord,vec2(-1.0, 0.0),frameSize).rgb); - float s20 = luminance(texOffset(sampler,texCoord,vec2(-1.0,-1.0),frameSize).rgb); - float s01 = luminance(texOffset(sampler,texCoord,vec2(-1.0, 1.0),frameSize).rgb); - float s21 = luminance(texOffset(sampler,texCoord,vec2( 0.0,-1.0),frameSize).rgb); - float s02 = luminance(texOffset(sampler,texCoord,vec2( 1.0, 1.0),frameSize).rgb); - float s12 = luminance(texOffset(sampler,texCoord,vec2( 1.0, 0.0),frameSize).rgb); - float s22 = luminance(texOffset(sampler,texCoord,vec2( 1.0,-1.0),frameSize).rgb); - - float sx = s00 + 2.0 * s10 + s20 - (s02 + 2.0 * s12 + s22); - float sy = s00 + 2.0 * s01 + s02 - (s20 + 2.0 * s21 + s22); - - return sx * sx + sy * sy; - ` - }, - - applyConvolution:{ - returnType:'vec4', name:'applyConvolution', params: { - texture:'sampler2D', texCoord:'vec2', texSize:'vec2', convMatrix:'float[9]', radius:'float' - }, body: ` - vec2 onePixel = vec2(1.0,1.0) / texSize * radius; - vec4 colorSum = - texture2D(texture, texCoord + onePixel * vec2(-1, -1)) * convMatrix[0] + - texture2D(texture, texCoord + onePixel * vec2( 0, -1)) * convMatrix[1] + - texture2D(texture, texCoord + onePixel * vec2( 1, -1)) * convMatrix[2] + - texture2D(texture, texCoord + onePixel * vec2(-1, 0)) * convMatrix[3] + - texture2D(texture, texCoord + onePixel * vec2( 0, 0)) * convMatrix[4] + - texture2D(texture, texCoord + onePixel * vec2( 1, 0)) * convMatrix[5] + - texture2D(texture, texCoord + onePixel * vec2(-1, 1)) * convMatrix[6] + - texture2D(texture, texCoord + onePixel * vec2( 0, 1)) * convMatrix[7] + - texture2D(texture, texCoord + onePixel * vec2( 1, 1)) * convMatrix[8]; - float kernelWeight = - convMatrix[0] + - convMatrix[1] + - convMatrix[2] + - convMatrix[3] + - convMatrix[4] + - convMatrix[5] + - convMatrix[6] + - convMatrix[7] + - convMatrix[8]; - if (kernelWeight <= 0.0) { - kernelWeight = 1.0; - } - return vec4((colorSum / kernelWeight).rgb, 1.0); - ` - } - } -})(); -(function() { - - class ShaderImpl extends bg.base.ShaderImpl { - initFlags(context) { - bg.base.ShaderType.VERTEX = context.VERTEX_SHADER; - bg.base.ShaderType.FRAGMENT = context.FRAGMENT_SHADER; - } - - setActive(context,shaderProgram) { - context.useProgram(shaderProgram && shaderProgram.program); - } - - create(context) { - return { - program:context.createProgram(), - attribLocations:{}, - uniformLocations:{} - }; - } - - addShaderSource(context,shaderProgram,shaderType,source) { - let error = null; - - if (!shaderProgram || !shaderProgram.program ) { - error = "Could not attach shader. Invalid shader program"; - } - else { - let shader = context.createShader(shaderType); - context.shaderSource(shader,source); - context.compileShader(shader); - - if (!context.getShaderParameter(shader, context.COMPILE_STATUS)) { - error = context.getShaderInfoLog(shader); - } - else { - context.attachShader(shaderProgram.program,shader); - } - - context.deleteShader(shader); - } - - return error; - } - - link(context,shaderProgram) { - let error = null; - if (!shaderProgram || !shaderProgram.program ) { - error = "Could not link shader. Invalid shader program"; - } - else { - context.linkProgram(shaderProgram.program); - if (!context.getProgramParameter(shaderProgram.program,context.LINK_STATUS)) { - error = context.getProgramInfoLog(shaderProgram.program); - } - } - return error; - } - - initVars(context,shader,inputBufferVars,valueVars) { - inputBufferVars.forEach(function(name) { - shader.attribLocations[name] = context.getAttribLocation(shader.program,name); - }); - - valueVars.forEach(function(name) { - shader.uniformLocations[name] = context.getUniformLocation(shader.program,name); - }); - } - - setInputBuffer(context,shader,varName,vertexBuffer,itemSize) { - if (vertexBuffer && shader && shader.program) { - let loc = shader.attribLocations[varName]; - if (loc!=-1) { - context.bindBuffer(context.ARRAY_BUFFER,vertexBuffer); - context.enableVertexAttribArray(loc); - context.vertexAttribPointer(loc,itemSize,context.FLOAT,false,0,0); - } - } - } - - disableInputBuffer(context,shader,name) { - context.disableVertexAttribArray(shader.attribLocations[name]); - } - - setValueInt(context,shader,name,v) { - context.uniform1i(shader.uniformLocations[name],v); - } - - setValueIntPtr(context,shader,name,v) { - context.uniform1iv(shader.uniformLocations[name],v); - } - - setValueFloat(context,shader,name,v) { - context.uniform1f(shader.uniformLocations[name],v); - } - - setValueFloatPtr(context,shader,name,v) { - context.uniform1fv(shader.uniformLocations[name],v); - } - - setValueVector2(context,shader,name,v) { - context.uniform2fv(shader.uniformLocations[name],v.v); - } - - setValueVector3(context,shader,name,v) { - context.uniform3fv(shader.uniformLocations[name],v.v); - } - - setValueVector4(context,shader,name,v) { - context.uniform4fv(shader.uniformLocations[name],v.v); - } - - setValueVector2v(context,shader,name,v) { - context.uniform2fv(shader.uniformLocations[name],v); - } - - setValueVector3v(context,shader,name,v) { - context.uniform3fv(shader.uniformLocations[name],v); - } - - setValueVector4v(context,shader,name,v) { - context.uniform4fv(shader.uniformLocations[name],v); - } - - setValueMatrix3(context,shader,name,traspose,v) { - context.uniformMatrix3fv(shader.uniformLocations[name],traspose,v.m); - } - - setValueMatrix4(context,shader,name,traspose,v) { - context.uniformMatrix4fv(shader.uniformLocations[name],traspose,v.m); - } - - setTexture(context,shader,name,texture,textureUnit) { - texture.setActive(textureUnit); - texture.bind(); - context.uniform1i(shader.uniformLocations[name],textureUnit); - } - } - - bg.webgl1.ShaderImpl = ShaderImpl; - -})(); - -(function() { - - class TextureImpl extends bg.base.TextureImpl { - initFlags(context) { - bg.base.TextureWrap.REPEAT = context.REPEAT; - bg.base.TextureWrap.CLAMP = context.CLAMP_TO_EDGE; - bg.base.TextureWrap.MIRRORED_REPEAT = context.MIRRORED_REPEAT; - - bg.base.TextureFilter.NEAREST_MIPMAP_NEAREST = context.NEAREST_MIPMAP_NEAREST; - bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST = context.LINEAR_MIPMAP_NEAREST; - bg.base.TextureFilter.NEAREST_MIPMAP_LINEAR = context.NEAREST_MIPMAP_LINEAR; - bg.base.TextureFilter.LINEAR_MIPMAP_LINEAR = context.LINEAR_MIPMAP_LINEAR; - bg.base.TextureFilter.NEAREST = context.NEAREST; - bg.base.TextureFilter.LINEAR = context.LINEAR; - - bg.base.TextureTarget.TEXTURE_2D = context.TEXTURE_2D; - bg.base.TextureTarget.CUBE_MAP = context.TEXTURE_CUBE_MAP; - bg.base.TextureTarget.POSITIVE_X_FACE = context.TEXTURE_CUBE_MAP_POSITIVE_X; - bg.base.TextureTarget.NEGATIVE_X_FACE = context.TEXTURE_CUBE_MAP_NEGATIVE_X; - bg.base.TextureTarget.POSITIVE_Y_FACE = context.TEXTURE_CUBE_MAP_POSITIVE_Y; - bg.base.TextureTarget.NEGATIVE_Y_FACE = context.TEXTURE_CUBE_MAP_NEGATIVE_Y; - bg.base.TextureTarget.POSITIVE_Z_FACE = context.TEXTURE_CUBE_MAP_POSITIVE_Z; - bg.base.TextureTarget.NEGATIVE_Z_FACE = context.TEXTURE_CUBE_MAP_NEGATIVE_Z; - } - - requireMipmaps(minFilter,magFilter) { - return minFilter==bg.base.TextureFilter.NEAREST_MIPMAP_NEAREST || - minFilter==bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST || - minFilter==bg.base.TextureFilter.NEAREST_MIPMAP_LINEAR || - minFilter==bg.base.TextureFilter.LINEAR_MIPMAP_LINEAR || - magFilter==bg.base.TextureFilter.NEAREST_MIPMAP_NEAREST || - magFilter==bg.base.TextureFilter.LINEAR_MIPMAP_NEAREST || - magFilter==bg.base.TextureFilter.NEAREST_MIPMAP_LINEAR || - magFilter==bg.base.TextureFilter.LINEAR_MIPMAP_LINEAR; - } - - create(context) { - return context.createTexture(); - } - - setActive(context,texUnit) { - context.activeTexture(context.TEXTURE0 + texUnit); - } - - bind(context,target,texture) { - context.bindTexture(target, texture); - } - - unbind(context,target) { - this.bind(context,target,null); - } - - setTextureWrapX(context,target,texture,wrap) { - context.texParameteri(target, context.TEXTURE_WRAP_S, wrap); - } - - setTextureWrapY(context,target,texture,wrap) { - context.texParameteri(target, context.TEXTURE_WRAP_T, wrap); - } - - setImage(context,target,minFilter,magFilter,texture,img,flipY) { - if (flipY) context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, true); - context.texParameteri(target, context.TEXTURE_MIN_FILTER, minFilter); - context.texParameteri(target, context.TEXTURE_MAG_FILTER, magFilter); - context.texImage2D(target,0,context.RGBA,context.RGBA,context.UNSIGNED_BYTE, img); - if (this.requireMipmaps(minFilter,magFilter)) { - context.generateMipmap(target); - } - } - - setImageRaw(context,target,minFilter,magFilter,texture,width,height,data,type,format) { - if (!type) { - type = context.RGBA; - } - if (!format) { - format = context.UNSIGNED_BYTE; - } - if (format==bg.base.RenderSurfaceFormat.FLOAT) { - minFilter = bg.base.TextureFilter.NEAREST; - magFilter = bg.base.TextureFilter.NEAREST; - } - context.texParameteri(target, context.TEXTURE_MIN_FILTER, minFilter); - context.texParameteri(target, context.TEXTURE_MAG_FILTER, magFilter); - context.texImage2D(target,0, type,width,height,0,type,format, data); - if (this.requireMipmaps(minFilter,magFilter)) { - context.generateMipmap(target); - } - } - - setTextureFilter(context,target,minFilter,magFilter) { - context.texParameteri(target,context.TEXTURE_MIN_FILTER,minFilter); - context.texParameteri(target,context.TEXTURE_MAG_FILTER,magFilter); - } - - setCubemapImage(context,face,image) { - context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, false); - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MIN_FILTER, bg.base.TextureFilter.LINEAR); - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MAG_FILTER, bg.base.TextureFilter.LINEAR); - context.texImage2D(face, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, image); - } - - setCubemapRaw(context,face,rawImage,w,h) { - let type = context.RGBA; - let format = context.UNSIGNED_BYTE; - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MIN_FILTER, bg.base.TextureFilter.LINEAR); - context.texParameteri(context.TEXTURE_CUBE_MAP, context.TEXTURE_MAG_FILTER, bg.base.TextureFilter.LINEAR); - context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, false); - context.texImage2D(face, 0, type, w, h, 0, type, format, rawImage); - } - - setVideo(context,target,texture,video,flipY) { - if (flipY) context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, false); - context.texParameteri(target, context.TEXTURE_MAG_FILTER, context.LINEAR); - context.texParameteri(target, context.TEXTURE_MIN_FILTER, context.LINEAR); - context.texParameteri(target, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE); - context.texParameteri(target, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE); - context.texImage2D(target,0,context.RGBA,context.RGBA,context.UNSIGNED_BYTE,video); - } - - updateVideoData(context,target,texture,video) { - context.bindTexture(target, texture); - context.texImage2D(target,0,context.RGBA,context.RGBA,context.UNSIGNED_BYTE,video); - context.bindTexture(target,null); - } - - destroy(context,texture) { - context.deleteTexture(this._texture); - } - } - - bg.webgl1.TextureImpl = TextureImpl; - -})(); \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/cookieconsent.min.js b/node_modules/paellaplayer/build/player/javascript/cookieconsent.min.js deleted file mode 100644 index 1e3dccf1a..000000000 --- a/node_modules/paellaplayer/build/player/javascript/cookieconsent.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e){if(!e.hasInitialised){var t={escapeRegExp:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},hasClass:function(e,t){var i=" ";return 1===e.nodeType&&(i+e.className+i).replace(/[\n\t]/g,i).indexOf(i+t+i)>=0},addClass:function(e,t){e.className+=" "+t},removeClass:function(e,t){var i=new RegExp("\\b"+this.escapeRegExp(t)+"\\b");e.className=e.className.replace(i,"")},interpolateString:function(e,t){return e.replace(/{{([a-z][a-z0-9\-_]*)}}/gi,function(e){return t(arguments[1])||""})},getCookie:function(e){var t=("; "+document.cookie).split("; "+e+"=");return t.length<2?void 0:t.pop().split(";").shift()},setCookie:function(e,t,i,n,o,s){var r=new Date;r.setHours(r.getHours()+24*(i||365));var a=[e+"="+t,"expires="+r.toUTCString(),"path="+(o||"/")];n&&a.push("domain="+n),s&&a.push("secure"),document.cookie=a.join(";")},deepExtend:function(e,t){for(var i in t)t.hasOwnProperty(i)&&(i in e&&this.isPlainObject(e[i])&&this.isPlainObject(t[i])?this.deepExtend(e[i],t[i]):e[i]=t[i]);return e},throttle:function(e,t){var i=!1;return function(){i||(e.apply(this,arguments),i=!0,setTimeout(function(){i=!1},t))}},hash:function(e){var t,i,n=0;if(0===e.length)return n;for(t=0,i=e.length;t=128?"#000":"#fff"},getLuminance:function(e){var t=parseInt(this.normaliseHex(e),16),i=38+(t>>16),n=38+(t>>8&255),o=38+(255&t);return"#"+(16777216+65536*(i<255?i<1?0:i:255)+256*(n<255?n<1?0:n:255)+(o<255?o<1?0:o:255)).toString(16).slice(1)},isMobile:function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)},isPlainObject:function(e){return"object"==typeof e&&null!==e&&e.constructor==Object},traverseDOMPath:function(e,i){return e&&e.parentNode?t.hasClass(e,i)?e:this.traverseDOMPath(e.parentNode,i):null}};e.status={deny:"deny",allow:"allow",dismiss:"dismiss"},e.transitionEnd=function(){var e=document.createElement("div"),t={t:"transitionend",OT:"oTransitionEnd",msT:"MSTransitionEnd",MozT:"transitionend",WebkitT:"webkitTransitionEnd"};for(var i in t)if(t.hasOwnProperty(i)&&void 0!==e.style[i+"ransition"])return t[i];return""}(),e.hasTransition=!!e.transitionEnd;var i=Object.keys(e.status).map(t.escapeRegExp);e.customStyles={},e.Popup=function(){var n={enabled:!0,container:null,cookie:{name:"cookieconsent_status",path:"/",domain:"",expiryDays:365,secure:!1},onPopupOpen:function(){},onPopupClose:function(){},onInitialise:function(e){},onStatusChange:function(e,t){},onRevokeChoice:function(){},onNoCookieLaw:function(e,t){},content:{header:"Cookies used on the website!",message:"This website uses cookies to ensure you get the best experience on our website.",dismiss:"Got it!",allow:"Allow cookies",deny:"Decline",link:"Learn more",href:"https://www.cookiesandyou.com",close:"❌",target:"_blank",policy:"Cookie Policy"},elements:{header:'{{header}} ',message:'{{message}}',messagelink:'{{message}} {{link}}',dismiss:'{{dismiss}}',allow:'{{allow}}',deny:'{{deny}}',link:'{{link}}',close:'{{close}}'},window:'',revokeBtn:'
            {{policy}}
            ',compliance:{info:'
            {{dismiss}}
            ',"opt-in":'
            {{deny}}{{allow}}
            ',"opt-out":'
            {{deny}}{{allow}}
            '},type:"info",layouts:{basic:"{{messagelink}}{{compliance}}","basic-close":"{{messagelink}}{{compliance}}{{close}}","basic-header":"{{header}}{{message}}{{link}}{{compliance}}"},layout:"basic",position:"bottom",theme:"block",static:!1,palette:null,revokable:!1,animateRevokable:!0,showLink:!0,dismissOnScroll:!1,dismissOnTimeout:!1,dismissOnWindowClick:!1,ignoreClicksFrom:["cc-revoke","cc-btn"],autoOpen:!0,autoAttach:!0,whitelistPage:[],blacklistPage:[],overrideHTML:null};function o(){this.initialise.apply(this,arguments)}function s(e){this.openingTimeout=null,t.removeClass(e,"cc-invisible")}function r(t){t.style.display="none",t.removeEventListener(e.transitionEnd,this.afterTransition),this.afterTransition=null}function a(){var e=this.options.position.split("-"),t=[];return e.forEach(function(e){t.push("cc-"+e)}),t}function c(n){var o=this.options,s=document.createElement("div"),r=o.container&&1===o.container.nodeType?o.container:document.body;s.innerHTML=n;var a=s.children[0];return a.style.display="none",t.hasClass(a,"cc-window")&&e.hasTransition&&t.addClass(a,"cc-invisible"),this.onButtonClick=function(n){var o=t.traverseDOMPath(n.target,"cc-btn")||n.target;if(t.hasClass(o,"cc-btn")){var s=o.className.match(new RegExp("\\bcc-("+i.join("|")+")\\b")),r=s&&s[1]||!1;r&&(this.setStatus(r),this.close(!0))}t.hasClass(o,"cc-close")&&(this.setStatus(e.status.dismiss),this.close(!0));t.hasClass(o,"cc-revoke")&&this.revokeChoice()}.bind(this),a.addEventListener("click",this.onButtonClick),o.autoAttach&&(r.firstChild?r.insertBefore(a,r.firstChild):r.appendChild(a)),a}function l(e){return"000000"==(e=t.normaliseHex(e))?"#222":t.getLuminance(e)}function u(e,t){for(var i=0,n=e.length;i=0;o&&t(n);return o}.call(this)&&(this.options.enabled=!1),u(this.options.blacklistPage,location.pathname)&&(this.options.enabled=!1),u(this.options.whitelistPage,location.pathname)&&(this.options.enabled=!0);var o=this.options.window.replace("{{classes}}",function(){var i=this.options,n="top"==i.position||"bottom"==i.position?"banner":"floating";t.isMobile()&&(n="floating");var o=["cc-"+n,"cc-type-"+i.type,"cc-theme-"+i.theme];i.static&&o.push("cc-static");o.push.apply(o,a.call(this));(function(i){var n=t.hash(JSON.stringify(i)),o="cc-color-override-"+n,s=t.isPlainObject(i);this.customStyleSelector=s?o:null,s&&function(i,n,o){if(e.customStyles[i])return void++e.customStyles[i].references;var s={},r=n.popup,a=n.button,c=n.highlight;r&&(r.text=r.text?r.text:t.getContrast(r.background),r.link=r.link?r.link:r.text,s[o+".cc-window"]=["color: "+r.text,"background-color: "+r.background],s[o+".cc-revoke"]=["color: "+r.text,"background-color: "+r.background],s[o+" .cc-link,"+o+" .cc-link:active,"+o+" .cc-link:visited"]=["color: "+r.link],a&&(a.text=a.text?a.text:t.getContrast(a.background),a.border=a.border?a.border:"transparent",s[o+" .cc-btn"]=["color: "+a.text,"border-color: "+a.border,"background-color: "+a.background],a.padding&&s[o+" .cc-btn"].push("padding: "+a.padding),"transparent"!=a.background&&(s[o+" .cc-btn:hover, "+o+" .cc-btn:focus"]=["background-color: "+(a.hover||l(a.background))]),c?(c.text=c.text?c.text:t.getContrast(c.background),c.border=c.border?c.border:"transparent",s[o+" .cc-highlight .cc-btn:first-child"]=["color: "+c.text,"border-color: "+c.border,"background-color: "+c.background]):s[o+" .cc-highlight .cc-btn:first-child"]=["color: "+r.text]));var u=document.createElement("style");document.head.appendChild(u),e.customStyles[i]={references:1,element:u.sheet};var h=-1;for(var p in s)s.hasOwnProperty(p)&&u.sheet.insertRule(p+"{"+s[p].join(";")+"}",++h)}(n,i,"."+o);return s}).call(this,this.options.palette);this.customStyleSelector&&o.push(this.customStyleSelector);return o}.call(this).join(" ")).replace("{{children}}",function(){var e={},i=this.options;i.showLink||(i.elements.link="",i.elements.messagelink=i.elements.message);Object.keys(i.elements).forEach(function(n){e[n]=t.interpolateString(i.elements[n],function(e){var t=i.content[e];return e&&"string"==typeof t&&t.length?t:""})});var n=i.compliance[i.type];n||(n=i.compliance.info);e.compliance=t.interpolateString(n,function(t){return e[t]});var o=i.layouts[i.layout];o||(o=i.layouts.basic);return t.interpolateString(o,function(t){return e[t]})}.call(this)),s=this.options.overrideHTML;if("string"==typeof s&&s.length&&(o=s),this.options.static){var r=c.call(this,'
            '+o+"
            ");r.style.display="",this.element=r.firstChild,this.element.style.display="none",t.addClass(this.element,"cc-invisible")}else this.element=c.call(this,o);(function(){var i=this.setStatus.bind(this),n=this.close.bind(this),o=this.options.dismissOnTimeout;"number"==typeof o&&o>=0&&(this.dismissTimeout=window.setTimeout(function(){i(e.status.dismiss),n(!0)},Math.floor(o)));var s=this.options.dismissOnScroll;if("number"==typeof s&&s>=0){var r=function(t){window.pageYOffset>Math.floor(s)&&(i(e.status.dismiss),n(!0),window.removeEventListener("scroll",r),this.onWindowScroll=null)};this.options.enabled&&(this.onWindowScroll=r,window.addEventListener("scroll",r))}var a=this.options.dismissOnWindowClick,c=this.options.ignoreClicksFrom;if(a){var l=function(o){for(var s=!1,r=o.path.length,a=c.length,u=0;uo&&(i=!0),i?t.hasClass(n,"cc-active")||t.addClass(n,"cc-active"):t.hasClass(n,"cc-active")&&t.removeClass(n,"cc-active")},200);this.onMouseMove=o,window.addEventListener("mousemove",o)}}}.call(this),this.options.autoOpen&&this.autoOpen()},o.prototype.destroy=function(){this.onButtonClick&&this.element&&(this.element.removeEventListener("click",this.onButtonClick),this.onButtonClick=null),this.dismissTimeout&&(clearTimeout(this.dismissTimeout),this.dismissTimeout=null),this.onWindowScroll&&(window.removeEventListener("scroll",this.onWindowScroll),this.onWindowScroll=null),this.onWindowClick&&(window.removeEventListener("click",this.onWindowClick),this.onWindowClick=null),this.onMouseMove&&(window.removeEventListener("mousemove",this.onMouseMove),this.onMouseMove=null),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.revokeBtn&&this.revokeBtn.parentNode&&this.revokeBtn.parentNode.removeChild(this.revokeBtn),this.revokeBtn=null,function(i){if(t.isPlainObject(i)){var n=t.hash(JSON.stringify(i)),o=e.customStyles[n];if(o&&!--o.references){var s=o.element.ownerNode;s&&s.parentNode&&s.parentNode.removeChild(s),e.customStyles[n]=null}}}(this.options.palette),this.options=null},o.prototype.open=function(t){if(this.element)return this.isOpen()||(e.hasTransition?this.fadeIn():this.element.style.display="",this.options.revokable&&this.toggleRevokeButton(),this.options.onPopupOpen.call(this)),this},o.prototype.close=function(t){if(this.element)return this.isOpen()&&(e.hasTransition?this.fadeOut():this.element.style.display="none",t&&this.options.revokable&&this.toggleRevokeButton(!0),this.options.onPopupClose.call(this)),this},o.prototype.fadeIn=function(){var i=this.element;if(e.hasTransition&&i&&(this.afterTransition&&r.call(this,i),t.hasClass(i,"cc-invisible"))){if(i.style.display="",this.options.static){var n=this.element.clientHeight;this.element.parentNode.style.maxHeight=n+"px"}this.openingTimeout=setTimeout(s.bind(this,i),20)}},o.prototype.fadeOut=function(){var i=this.element;e.hasTransition&&i&&(this.openingTimeout&&(clearTimeout(this.openingTimeout),s.bind(this,i)),t.hasClass(i,"cc-invisible")||(this.options.static&&(this.element.parentNode.style.maxHeight=""),this.afterTransition=r.bind(this,i),i.addEventListener(e.transitionEnd,this.afterTransition),t.addClass(i,"cc-invisible")))},o.prototype.isOpen=function(){return this.element&&""==this.element.style.display&&(!e.hasTransition||!t.hasClass(this.element,"cc-invisible"))},o.prototype.toggleRevokeButton=function(e){this.revokeBtn&&(this.revokeBtn.style.display=e?"":"none")},o.prototype.revokeChoice=function(e){this.options.enabled=!0,this.clearStatus(),this.options.onRevokeChoice.call(this),e||this.autoOpen()},o.prototype.hasAnswered=function(t){return Object.keys(e.status).indexOf(this.getStatus())>=0},o.prototype.hasConsented=function(t){var i=this.getStatus();return i==e.status.allow||i==e.status.dismiss},o.prototype.autoOpen=function(e){!this.hasAnswered()&&this.options.enabled?this.open():this.hasAnswered()&&this.options.revokable&&this.toggleRevokeButton(!0)},o.prototype.setStatus=function(i){var n=this.options.cookie,o=t.getCookie(n.name),s=Object.keys(e.status).indexOf(o)>=0;Object.keys(e.status).indexOf(i)>=0?(t.setCookie(n.name,i,n.expiryDays,n.domain,n.path,n.secure),this.options.onStatusChange.call(this,i,s)):this.clearStatus()},o.prototype.getStatus=function(){return t.getCookie(this.options.cookie.name)},o.prototype.clearStatus=function(){var e=this.options.cookie;t.setCookie(e.name,"",-1,e.domain,e.path)},o}(),e.Location=function(){var e={timeout:5e3,services:["ipinfo"],serviceDefinitions:{ipinfo:function(){return{url:"//ipinfo.io",headers:["Accept: application/json"],callback:function(e,t){try{var i=JSON.parse(t);return i.error?s(i):{code:i.country}}catch(e){return s({error:"Invalid response ("+e+")"})}}}},ipinfodb:function(e){return{url:"//api.ipinfodb.com/v3/ip-country/?key={api_key}&format=json&callback={callback}",isScript:!0,callback:function(e,t){try{var i=JSON.parse(t);return"ERROR"==i.statusCode?s({error:i.statusMessage}):{code:i.countryCode}}catch(e){return s({error:"Invalid response ("+e+")"})}}}},maxmind:function(){return{url:"//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js",isScript:!0,callback:function(e){window.geoip2?geoip2.country(function(t){try{e({code:t.country.iso_code})}catch(t){e(s(t))}},function(t){e(s(t))}):e(new Error("Unexpected response format. The downloaded script should have exported `geoip2` to the global scope"))}}}}};function i(i){t.deepExtend(this.options={},e),t.isPlainObject(i)&&t.deepExtend(this.options,i),this.currentServiceIndex=-1}function n(e,t,i){var n,o=document.createElement("script");o.type="text/"+(e.type||"javascript"),o.src=e.src||e,o.async=!1,o.onreadystatechange=o.onload=function(){var e=o.readyState;clearTimeout(n),t.done||e&&!/loaded|complete/.test(e)||(t.done=!0,t(),o.onreadystatechange=o.onload=null)},document.body.appendChild(o),n=setTimeout(function(){t.done=!0,t(),o.onreadystatechange=o.onload=null},i)}function o(e,t,i,n,o){var s=new(window.XMLHttpRequest||window.ActiveXObject)("MSXML2.XMLHTTP.3.0");if(s.open(n?"POST":"GET",e,1),s.setRequestHeader("Content-type","application/x-www-form-urlencoded"),Array.isArray(o))for(var r=0,a=o.length;r3&&t(s)}),s.send(n)}function s(e){return new Error("Error ["+(e.code||"UNKNOWN")+"]: "+e.error)}return i.prototype.getNextService=function(){var e;do{e=this.getServiceByIdx(++this.currentServiceIndex)}while(this.currentServiceIndex=0,revokable:t.revokable.indexOf(e)>=0,explicitAction:t.explicitAction.indexOf(e)>=0}},i.prototype.applyLaw=function(e,t){var i=this.get(t);return i.hasLaw||(e.enabled=!1,"function"==typeof e.onNoCookieLaw&&e.onNoCookieLaw(t,i)),this.options.regionalLaw&&(i.revokable&&(e.revokable=!0),i.explicitAction&&(e.dismissOnScroll=!1,e.dismissOnTimeout=!1)),e},i}(),e.initialise=function(i,n,o){var s=new e.Law(i.law);n||(n=function(){}),o||(o=function(){});var r=Object.keys(e.status),a=t.getCookie("cookieconsent_status");r.indexOf(a)>=0?n(new e.Popup(i)):e.getCountryCode(i,function(t){delete i.law,delete i.location,t.code&&(i=s.applyLaw(i,t.code)),n(new e.Popup(i))},function(t){delete i.law,delete i.location,o(t,new e.Popup(i))})},e.getCountryCode=function(t,i,n){t.law&&t.law.countryCode?i({code:t.law.countryCode}):t.location?new e.Location(t.location).locate(function(e){i(e||{})},n):i({})},e.utils=t,e.hasInitialised=!0,window.cookieconsent=e}}(window.cookieconsent||{}); \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/hls.min.js b/node_modules/paellaplayer/build/player/javascript/hls.min.js deleted file mode 100644 index e26445079..000000000 --- a/node_modules/paellaplayer/build/player/javascript/hls.min.js +++ /dev/null @@ -1,2 +0,0 @@ -"undefined"!=typeof window&&function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hls=e():t.Hls=e()}(this,(function(){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var n=e[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=t,r.c=e,r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)r.d(i,n,function(e){return t[e]}.bind(null,n));return i},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/dist/",r(r.s=20)}([function(t,e,r){"use strict";var i;r.d(e,"a",(function(){return i})),function(t){t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},function(t,e,r){"use strict";r.d(e,"a",(function(){return o})),r.d(e,"b",(function(){return l}));var i=function(){},n={trace:i,debug:i,log:i,warn:i,info:i,error:i},a=n;function s(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):i}function o(t){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>8*(15-r)&255;return e},r.setDecryptDataFromLevelKey=function(t,e){var r=t;return"AES-128"===(null==t?void 0:t.method)&&t.uri&&!t.iv&&((r=o.a.fromURI(t.uri)).method=t.method,r.iv=this.createInitializationVector(e),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(t,e,r,i,n,a){void 0===a&&(a=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:n,partial:a}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null},c(e,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var t=this.sn;"number"!=typeof t&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.b.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),t=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,t)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(n.a)(this.programDateTime))return null;var t=Object(n.a)(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;return!(null===(t=this.decryptdata)||void 0===t||!t.keyFormat||!this.decryptdata.uri)}}]),e}(f),v=function(t){function e(e,r,i,n,a){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.a,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=n;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return u(e,t),c(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(f)},function(t,e,r){"use strict";r.d(e,"b",(function(){return h})),r.d(e,"g",(function(){return d})),r.d(e,"f",(function(){return c})),r.d(e,"d",(function(){return f})),r.d(e,"c",(function(){return g})),r.d(e,"e",(function(){return p})),r.d(e,"h",(function(){return m})),r.d(e,"a",(function(){return y}));var i=r(9),n=r(5),a=Math.pow(2,32)-1,s=[].push;function o(t){return String.fromCharCode.apply(null,t)}function l(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function u(t,e,r){"data"in t&&(e+=t.start,t=t.data),t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function h(t,e){var r,i,n,a=[];if(!e.length)return a;"data"in t?(r=t.data,i=t.start,n=t.end):(i=0,n=(r=t).byteLength);for(var u=i;u1?u+d:n;if(o(r.subarray(u+4,u+8))===e[0])if(1===e.length)a.push({data:r,start:u+8,end:c});else{var f=h({data:r,start:u+8,end:c},e.slice(1));f.length&&s.apply(a,f)}u=c}return a}function d(t){var e=h(t,["moov"])[0],r=e?e.end:null,i=h(t,["sidx"]);if(!i||!i[0])return null;var n=[],a=i[0],s=a.data[0],o=0===s?8:16,u=l(a,o);o+=4;o+=0===s?8:16,o+=2;var d=a.end+0,c=function(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r}(a,o);o+=2;for(var f=0;f>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var m=l(a,g);g+=4,n.push({referenceSize:p,subsegmentDuration:m,info:{duration:m/u,start:d,end:d+p-1}}),d+=p,o=g+=4}return{earliestPresentationTime:0,timescale:u,version:s,referencesCount:c,references:n,moovEndOffset:r}}function c(t){for(var e=[],r=h(t,["moov","trak"]),i=0;i0)return t.subarray(r,r+i)},o=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},l=function(t,e){return n(t,e)&&o(t,e+6)+10<=t.length-e},u=function(t){for(var e=c(t),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(a);break;case 12:case 13:s=t[h++],u+=String.fromCharCode((31&a)<<6|63&s);break;case 14:s=t[h++],o=t[h++],u+=String.fromCharCode((15&a)<<12|(63&s)<<6|(63&o)<<0)}}return u};function T(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},function(t,e,r){"use strict";r.d(e,"c",(function(){return n})),r.d(e,"b",(function(){return a})),r.d(e,"a",(function(){return s}));function i(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=t*e*r;return i?Math.round(n):n}function n(t,e,r,n){return void 0===r&&(r=1),void 0===n&&(n=!1),i(t,e,1/r,n)}function a(t,e){return void 0===e&&(e=!1),i(t,1e3,1/9e4,e)}function s(t,e){return void 0===e&&(e=1),i(t,9e4,1/e)}},function(t,e,r){"use strict";function i(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}r.d(e,"a",(function(){return i}))},function(t,e,r){"use strict";r.d(e,"c",(function(){return lt})),r.d(e,"d",(function(){return ht})),r.d(e,"a",(function(){return dt})),r.d(e,"b",(function(){return ct}));var i=r(0),n=r(2),a=r(15),s=r(3),o=r(7);var l=r(6),u=r(9),h=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(){},e.resetContiguity=function(){},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=Object(l.a)(this.cachedData,t),this.cachedData=null);var r,i,n=o.b(t,0),a=n?n.length:0,s=this._audioTrack,h=this._id3Track,c=n?o.d(n):void 0,f=t.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=d(c,e)),n&&n.length>0&&h.samples.push({pts:this.initPTS,dts:this.initPTS,data:n}),i=this.initPTS;a>>5}function m(t,e){return e+1=t.length)return!1;var i=p(t,e);if(i<=r)return!1;var n=e+i;return n===t.length||m(t,n)}return!1}function T(t,e,r,a,s){if(!t.samplerate){var o=function(t,e,r,a){var s,o,l,u,h=navigator.userAgent.toLowerCase(),d=a,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[r+2])>>>6);var g=(60&e[r+2])>>>2;if(!(g>c.length-1))return l=(1&e[r+2])<<2,l|=(192&e[r+3])>>>6,f.b.log("manifest codec:"+a+", ADTS type:"+s+", samplingIndex:"+g),/firefox/i.test(h)?g>=6?(s=5,u=new Array(4),o=g-3):(s=2,u=new Array(2),o=g):-1!==h.indexOf("android")?(s=2,u=new Array(2),o=g):(s=5,u=new Array(4),a&&(-1!==a.indexOf("mp4a.40.29")||-1!==a.indexOf("mp4a.40.5"))||!a&&g>=6?o=g-3:((a&&-1!==a.indexOf("mp4a.40.2")&&(g>=6&&1===l||/vivaldi/i.test(h))||!a&&1===l)&&(s=2,u=new Array(2)),o=g)),u[0]=s<<3,u[0]|=(14&g)>>1,u[1]|=(1&g)<<7,u[1]|=l<<3,5===s&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:c[g],channelCount:l,codec:"mp4a.40."+s,manifestCodec:d};t.trigger(i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+g})}(e,r,a,s);if(!o)return;t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,f.b.log("parsed codec:"+t.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function b(t){return 9216e4/t}function E(t,e,r,i,n){var a=function(t,e,r,i,n){var a=v(t,e),s=p(t,e);if((s-=a)>0)return{headerLength:a,frameLength:s,stamp:r+i*n}}(e,r,i,n,b(t.samplerate));if(a){var s,o=a.frameLength,l=a.headerLength,u=a.stamp,h=l+o,d=Math.max(0,r+h-e.length);d?(s=new Uint8Array(h-l)).set(e.subarray(r+l,e.length),0):s=e.subarray(r+l,r+h);var c={unit:s,pts:u};return d||t.samples.push(c),{sample:c,length:h,missing:d}}}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}var L=function(t){var e,r;function i(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var n=i.prototype;return n.resetInitSegment=function(e,r,i){t.prototype.resetInitSegment.call(this,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,isAAC:!0,samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(o.b(t,0)||[]).length,r=t.length;e0},e.demux=function(t){var e=t,r={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};if(this.config.progressive){this.remainderData&&(e=Object(l.a)(this.remainderData,t));var i=Object(l.h)(e);this.remainderData=i.remainder,r.samples=i.valid||new Uint8Array}else r.samples=e;return{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:r,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.flush=function(){var t={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};return t.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:t,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}();R.minProbeByteLength=1024;var D=R,k=null,_=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],I=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],C=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],w=[0,1,1,4];function O(t,e,r,i,n){if(!(r+24>e.length)){var a=x(e,r);if(a&&r+a.frameLength<=e.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:e.subarray(r,r+a.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=a.channelCount,t.samplerate=a.sampleRate,t.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function x(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,n=t[e+2]>>4&15,a=t[e+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*_[14*(3===r?3-i:3===i?3:4)+n-1],u=I[3*(3===r?0:2===r?1:2)+a],h=3===o?1:2,d=C[r][i],c=w[i],f=8*d*c,g=Math.floor(d*l/u+s)*c;if(null===k){var v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);k=v?parseInt(v[1]):0}return!!k&&k<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:h,frameLength:g,samplesPerFrame:f}}}function P(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function M(t,e){return e+1t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&f.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,n=32;n=t.length)return void i();for(var n=t[e].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,a,s),!s)return}}}},t}(),B={video:1,audio:2,id3:3,text:4},G=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this.aacLastPTS=null,this._initPTS=null,this._initDTS=null,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return!(r<0)&&(r&&f.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},t.syncOffset=function(t){for(var e=Math.min(1e3,t.length-564),r=0;r>4>1){if((_=R+5+e[R+4])===R+188)continue}else _=R+4;switch(k){case c:D&&(g&&(o=V(g))&&this.parseAVCPES(o,!1),g={data:[],size:0}),g&&(g.data.push(e.subarray(_,R+188)),g.size+=R+188-_);break;case v:D&&(m&&(o=V(m))&&(h.isAAC?this.parseAACPES(o):this.parseMPEGPES(o)),m={data:[],size:0}),m&&(m.data.push(e.subarray(_,R+188)),m.size+=R+188-_);break;case p:D&&(y&&(o=V(y))&&this.parseID3PES(o),y={data:[],size:0}),y&&(y.data.push(e.subarray(_,R+188)),y.size+=R+188-_);break;case 0:D&&(_+=e[_]+1),E=this._pmtId=j(e,_);break;case E:D&&(_+=e[_]+1);var I=H(e,_,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,a);(c=I.avc)>0&&(u.pid=c),(v=I.audio)>0&&(h.pid=v,h.isAAC=I.isAAC),(p=I.id3)>0&&(d.pid=p),T&&!b&&(f.b.log("reparse from beginning"),T=!1,R=L-188),b=this.pmtParsed=!0;break;case 17:case 8191:break;default:T=!0}}else A++;A>0&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!1,reason:"Found "+A+" TS packet/s that do not start with 0x47"}),u.pesData=g,h.pesData=m,d.pesData=y;var C={audioTrack:h,avcTrack:u,id3Track:d,textTrack:this._txtTrack};return s&&this.extractRemainingSamples(C),C},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{audioTrack:this._audioTrack,avcTrack:this._avcTrack,textTrack:this._txtTrack,id3Track:this._id3Track},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.avcTrack,n=t.id3Track,a=i.pesData,s=r.pesData,o=n.pesData;a&&(e=V(a))?(this.parseAVCPES(e,!0),i.pesData=null):i.pesData=a,s&&(e=V(s))?(r.isAAC?this.parseAACPES(e):this.parseMPEGPES(e),r.pesData=null):(null!=s&&s.size&&f.b.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s),o&&(e=V(o))?(this.parseID3PES(e),n.pesData=null):n.pesData=o},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),n=this.sampleAes=new U(this.observer,this.config,e);return this.decrypt(i,n)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,n=t.avcTrack;i.samples&&i.isAAC?e.decryptAacSamples(i.samples,0,(function(){n.samples?e.decryptAvcSamples(n.samples,0,0,(function(){r(t)})):r(t)})):n.samples&&e.decryptAvcSamples(n.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._initPTS=this._initDTS=null,this._duration=0},e.parseAVCPES=function(t,e){var r,i=this,n=this._avcTrack,a=this.parseAVCNALu(t.data),s=this.avcSample,l=!1;t.data=null,s&&a.length&&!n.audFound&&(W(s,n),s=this.avcSample=K(!1,t.pts,t.dts,"")),a.forEach((function(e){switch(e.type){case 1:r=!0,s||(s=i.avcSample=K(!0,t.pts,t.dts,"")),s.frame=!0;var a=e.data;if(l&&a.length>4){var u=new N(a).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(s.key=!0)}break;case 5:r=!0,s||(s=i.avcSample=K(!0,t.pts,t.dts,"")),s.key=!0,s.frame=!0;break;case 6:r=!0;var h=new N(q(e.data));h.readUByte();for(var d=0,c=0,f=!1,g=0;!f&&h.bytesAvailable>1;){d=0;do{d+=g=h.readUByte()}while(255===g);c=0;do{c+=g=h.readUByte()}while(255===g);if(4===d&&0!==h.bytesAvailable){if(f=!0,181===h.readUByte())if(49===h.readUShort())if(1195456820===h.readUInt())if(3===h.readUByte()){for(var v=h.readUByte(),p=31&v,m=[v,h.readUByte()],y=0;y16){for(var T=[],b=0;b<16;b++)T.push(h.readUByte().toString(16)),3!==b&&5!==b&&7!==b&&9!==b||T.push("-");for(var E=c-16,S=new Uint8Array(E),L=0;L=0){var d={data:t.subarray(u,l-a-1),type:h};o.push(d)}else{var c=this.getLastNalUnit();if(c&&(s&&l<=4-s&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-s)),(r=l-a-1)>0)){var f=new Uint8Array(c.data.byteLength+r);f.set(c.data,0),f.set(t.subarray(0,r),c.data.byteLength),c.data=f,c.state=0}}l=0&&a>=0){var g={data:t.subarray(u,i),type:h,state:a};o.push(g)}if(0===o.length){var v=this.getLastNalUnit();if(v){var p=new Uint8Array(v.data.byteLength+t.byteLength);p.set(v.data,0),p.set(t,v.data.byteLength),v.data=p}}return n.naluState=a,o},e.parseAACPES=function(t){var e,r,a,s,o,l=0,u=this._audioTrack,h=this.aacOverFlow,d=t.data;if(h){this.aacOverFlow=null;var c=h.sample.unit.byteLength,g=Math.min(h.missing,c),v=c-g;h.sample.unit.set(d.subarray(0,g),v),u.samples.push(h.sample),l=h.missing}for(e=l,r=d.length;e1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?n-(a=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(f.b.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var h=(i=e[8])+9;if(t.size<=h)return null;t.size-=h;for(var d=new Uint8Array(t.size),c=0,g=o.length;cv){h-=v;continue}e=e.subarray(h),v-=h,h=0}d.set(e,s),s+=v}return r&&(r-=i+3),{data:d,pts:n,dts:a,len:r}}return null}function W(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var n=r[i-1];t.pts=n.pts,t.dts=n.dts}e.samples.push(t)}t.debug.length&&f.b.log(t.pts+"/"+t.dts+":"+t.debug)}function Y(t,e){var r=t.length;if(r>0){if(e.pts>=t[r-1].pts)t.push(e);else for(var i=r-1;i>=0;i--)if(e.pts0?this.lastEndDTS=p:(f.b.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var m=!!c.audio,y=!!c.video,T="";m&&(T+="audio"),y&&(T+="video");var b={data1:h,startPTS:v,startDTS:v,endPTS:p,endDTS:p,type:T,hasAudio:m,hasVideo:y,nb:1,dropped:0};return u.audio="audio"===b.type?b:void 0,u.video="audio"!==b.type?b:void 0,u.text=i,u.id3=r,u.initSegment=d,u},t}(),et=function(t,e,r){return Object(l.d)(t,e)-r};function rt(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===Z.a.VIDEO?"avc1.42e01e":"mp4a.40.5"}var it,nt=tt,at=r(13);try{it=self.performance.now.bind(self.performance)}catch(t){f.b.debug("Unable to use Performance API on this environment"),it=self.Date.now}var st=[{demux:X,remux:J.a},{demux:D,remux:nt},{demux:A,remux:J.a},{demux:$,remux:J.a}],ot=1024;st.forEach((function(t){var e=t.demux;ot=Math.max(ot,e.minProbeByteLength)}));var lt=function(){function t(t,e,r,i,n){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.cache=new at.a,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=n}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var n=this,a=r.transmuxing;a.executeStart=it();var s=new Uint8Array(t),o=this.cache,u=this.config,h=this.currentTransmuxState,d=this.transmuxConfig;i&&(this.currentTransmuxState=i);var c=function(t,e){var r=null;t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e);return r}(s,e);if(c&&"AES-128"===c.method){var f=this.getDecrypter();if(!u.enableSoftwareAES)return this.decryptionPromise=f.webCryptoDecrypt(s,c.key.buffer,c.iv.buffer).then((function(t){var e=n.push(t,null,r);return n.decryptionPromise=null,e})),this.decryptionPromise;var g=f.softwareDecrypt(s,c.key.buffer,c.iv.buffer);if(!g)return a.executeEnd=it(),ut(r);s=new Uint8Array(g)}var v=i||h,p=v.contiguous,m=v.discontinuity,y=v.trackSwitch,T=v.accurateTimeOffset,b=v.timeOffset,E=v.initSegmentChange,S=d.audioCodec,L=d.videoCodec,A=d.defaultInitPts,R=d.duration,D=d.initSegmentData;if((m||y||E)&&this.resetInitSegment(D,S,L,R),(m||E)&&this.resetInitialTimestamp(A),p||this.resetContiguity(),this.needsProbing(s,m,y)){if(o.dataLength){var k=o.flush();s=Object(l.a)(k,s)}this.configureTransmuxer(s,d)}var _=this.transmux(s,c,b,T,r),I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,a.executeEnd=it(),_},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=it();var a=this.decrypter,s=this.cache,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return e.flush(t)}));var u=[],h=o.timeOffset;if(a){var d=a.flush();d&&u.push(this.push(d,null,t))}var c=s.dataLength;s.reset();var f=this.demuxer,g=this.remuxer;if(!f||!g)return c>=ot&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=it(),[ut(t)];var v=f.flush(h);return ht(v)?v.then((function(r){return e.flushRemux(u,r,t),u})):(this.flushRemux(u,v,t),u)},e.flushRemux=function(t,e,r){var i=e.audioTrack,n=e.avcTrack,a=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;f.b.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var h=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);t.push({remuxResult:h,chunkMeta:r}),r.transmuxing.executeEnd=it()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(e,r,i),a.resetInitSegment(t,e,r))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,n){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,n):this.transmuxUnencrypted(t,r,i,n)},e.transmuxUnencrypted=function(t,e,r,i){var n=this.demuxer.demux(t,e,!1,!this.config.progressive),a=n.audioTrack,s=n.avcTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,n){var a=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:a.remuxer.remux(t.audioTrack,t.avcTrack,t.id3Track,t.textTrack,r,i,!1,a.id),chunkMeta:n}}))},e.configureTransmuxer=function(t,e){for(var r,i=this.config,n=this.observer,a=this.typeSupported,s=this.vendor,o=e.audioCodec,l=e.defaultInitPts,u=e.duration,h=e.initSegmentData,d=e.videoCodec,c=0,g=st.length;c>>8^255&p^99,t[f]=p,e[p]=f;var m=c[f],y=c[m],T=c[y],b=257*c[p]^16843008*p;i[f]=b<<24|b>>>8,n[f]=b<<16|b>>>16,a[f]=b<<8|b>>>24,s[f]=b,b=16843009*T^65537*y^257*m^16843008*f,l[p]=b<<24|b>>>8,u[p]=b<<16|b>>>16,h[p]=b<<8|b>>>24,d[p]=b,f?(f=m^c[c[c[T^m]]],g^=c[c[g]]):f=g=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i1?r-1:0),n=1;n>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),a=0,e=8;a>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(a+1)),n=Math.floor(r%(a+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,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,255,255,255,255]);return t.box(t.types.mvhd,s)},t.sdtp=function(e){var r,i,n=e.samples||[],a=new Uint8Array(4+n.length);for(r=0;r>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|e.sps.length].concat(a).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,n=e.width,s=e.height,o=Math.floor(i/(a+1)),l=Math.floor(i%(a+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,s>>8&255,255&s,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),n=e.id,s=Math.floor(r/(a+1)),o=Math.floor(r%(a+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,n,a,s,o,l,u=e.samples||[],h=u.length,d=12+16*h,c=new Uint8Array(d);for(r+=8+d,c.set([0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();s.types=void 0,s.HDLR_TYPES=void 0,s.STTS=void 0,s.STSC=void 0,s.STCO=void 0,s.STSZ=void 0,s.VMHD=void 0,s.SMHD=void 0,s.STSD=void 0,s.FTYP=void 0,s.DINF=void 0;var o=s,l=r(0),u=r(2),h=r(1),d=r(4),c=r(8);function f(){return(f=Object.assign||function(t){for(var e=1;e0?t:r.pts}),t[0].pts);return e&&h.b.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,n,a,s,o){var l,u,c,f,g,v,p=n,m=n,T=t.pid>-1,b=e.pid>-1,E=e.samples.length,S=t.samples.length>0,L=E>1;if((!T||S)&&(!b||L)||this.ISGenerated||s){this.ISGenerated||(c=this.generateIS(t,e,n));var A=this.isVideoContiguous,R=-1;if(L&&(R=function(t){for(var e=0;e0){h.b.warn("[mp4-remuxer]: Dropped "+R+" out of "+E+" video samples due to a missing keyframe");var D=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(R),e.dropped+=R,m+=(e.samples[0].pts-D)/(e.timescale||9e4)}else-1===R&&(h.b.warn("[mp4-remuxer]: No keyframe found out of "+E+" video samples"),v=!1);if(this.ISGenerated){if(S&&L){var k=this.getVideoStartPts(e.samples),_=(y(t.samples[0].pts,k)-k)/e.inputTimeScale;p+=Math.max(0,_),m+=Math.max(0,-_)}if(S){if(t.samplerate||(h.b.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(t,e,n)),u=this.remuxAudio(t,p,this.isAudioContiguous,a,b||L||o===d.b.AUDIO?m:void 0),L){var I=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(h.b.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(t,e,n)),l=this.remuxVideo(e,m,A,I)}}else L&&(l=this.remuxVideo(e,m,A,0));l&&(l.firstKeyFrame=R,l.independent=-1!==R)}}return this.ISGenerated&&(r.samples.length&&(g=this.remuxID3(r,n)),i.samples.length&&(f=this.remuxText(i,n))),{audio:u,video:l,initSegment:c,independent:v,text:f,id3:g}},e.generateIS=function(t,e,r){var n,a,s,l=t.samples,u=e.samples,h=this.typeSupported,d={},c=!Object(i.a)(this._initPTS),f="audio/mp4";if(c&&(n=a=1/0),t.config&&l.length&&(t.timescale=t.samplerate,t.isAAC||(h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3")),d.audio={id:"audio",container:f,codec:t.codec,initSegment:!t.isAAC&&h.mpeg?new Uint8Array(0):o.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(s=t.inputTimeScale,n=a=l[0].pts-Math.round(s*r))),e.sps&&e.pps&&u.length&&(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:o.initSegment([e]),metadata:{width:e.width,height:e.height}},c)){s=e.inputTimeScale;var g=this.getVideoStartPts(u),v=Math.round(s*r);a=Math.min(a,y(u[0].dts,g)-v),n=Math.min(n,g-v)}if(Object.keys(d).length)return this.ISGenerated=!0,c&&(this._initPTS=n,this._initDTS=a),{tracks:d,initPTS:n,timescale:s}},e.remuxVideo=function(t,e,r,i){var n,a,s,d=t.inputTimeScale,v=t.samples,m=[],b=v.length,E=this._initPTS,S=this.nextAvcDts,L=8,A=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,D=0,k=!1;r&&null!==S||(S=e*d-(v[0].pts-y(v[0].dts,v[0].pts)));for(var _=0;_I.pts){D=Math.max(Math.min(D,I.pts-I.dts),-18e3)}I.dts0?_-1:_].dts&&(k=!0)}k&&v.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),a=v[0].dts,s=v[v.length-1].dts;var C=Math.round((s-a)/(b-1));if(D<0){if(D<-2*C){h.b.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+Object(c.b)(-C,!0)+" ms");for(var w=D,O=0;OC;if(M||P<-1){M?h.b.warn("AVC: "+Object(c.b)(P,!0)+" ms ("+P+"dts) hole between fragments detected, filling it"):h.b.warn("AVC: "+Object(c.b)(-P,!0)+" ms ("+P+"dts) overlapping between fragments detected"),a=S;var F=v[0].pts-P;v[0].dts=a,v[0].pts=F,h.b.log("Video: First PTS/DTS adjusted: "+Object(c.b)(F,!0)+"/"+Object(c.b)(a,!0)+", delta: "+Object(c.b)(P,!0)+" ms")}}p&&(a=Math.max(0,a));for(var N=0,U=0,B=0;B0?X-1:X].dts;if(it.stretchShortVideoTrack&&null!==this.nextAudioPts){var at=Math.floor(it.maxBufferHole*d),st=(i?A+i*d:this.nextAudioPts)-z.pts;st>at?((n=st-nt)<0&&(n=nt),h.b.log("[mp4-remuxer]: It is approximately "+st/90+" ms to the next segment; using duration "+n/90+" ms for the last video frame.")):n=nt}else n=nt}var ot=Math.round(z.pts-z.dts);m.push(new T(z.key,n,$,ot))}if(m.length&&g&&g<70){var lt=m[0].flags;lt.dependsOn=2,lt.isNonSync=0}this.nextAvcDts=S=s+n,this.isVideoContiguous=!0;var ut={data1:o.moof(t.sequenceNumber++,a,f({},t,{samples:m})),data2:W,startPTS:A/d,endPTS:(R+n)/d,startDTS:a/d,endDTS:S/d,type:"video",hasAudio:!1,hasVideo:!0,nb:m.length,dropped:t.dropped};return t.samples=[],t.dropped=0,ut},e.remuxAudio=function(t,e,r,i,a){var s=t.inputTimeScale,d=s/(t.samplerate?t.samplerate:s),c=t.isAAC?1024:1152,g=c*d,v=this._initPTS,p=!t.isAAC&&this.typeSupported.mpeg,m=[],b=t.samples,E=p?0:8,S=this.nextAudioPts||-1,L=e*s;if(this.isAudioContiguous=r=r||b.length&&S>0&&(i&&Math.abs(L-S)<9e3||Math.abs(y(b[0].pts-v,L)-S)<20*g),b.forEach((function(t){t.pts=y(t.pts-v,L)})),!r||S<0){if(!(b=b.filter((function(t){return t.pts>=0}))).length)return;S=0===a?0:i?Math.max(0,L):b[0].pts}if(t.isAAC)for(var A=void 0!==a,R=this.config.maxAudioFramesDrift,D=0,k=S;D=R*g&&w<1e4&&A){var O=Math.round(C/g);(k=I-O*g)<0&&(O--,k+=g),0===D&&(this.nextAudioPts=S=k),h.b.warn("[mp4-remuxer]: Injecting "+O+" audio frame @ "+(k/s).toFixed(3)+"s due to "+Math.round(1e3*C/s)+" ms gap.");for(var x=0;x0))return;B+=E;try{F=new Uint8Array(B)}catch(t){return void this.observer.emit(l.a.ERROR,l.a.ERROR,{type:u.b.MUX_ERROR,details:u.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:B,reason:"fail allocating audio mdat "+B})}p||(new DataView(F.buffer).setUint32(0,B),F.set(o.types.mdat,4))}F.set(V,E);var Y=V.byteLength;E+=Y,m.push(new T(!0,c,Y,0)),U=W}var q=m.length;if(q){var X=m[m.length-1];this.nextAudioPts=S=U+d*X.duration;var z=p?new Uint8Array(0):o.moof(t.sequenceNumber++,N/d,f({},t,{samples:m}));t.samples=[];var Q=N/s,$=S/s,J={data1:z,data2:F,startPTS:Q,endPTS:$,startDTS:Q,endDTS:$,type:"audio",hasAudio:!0,hasVideo:!1,nb:q};return this.isAudioContiguous=!0,J}},e.remuxEmptyAudio=function(t,e,r,i){var a=t.inputTimeScale,s=a/(t.samplerate?t.samplerate:a),o=this.nextAudioPts,l=(null!==o?o:i.startDTS*a)+this._initDTS,u=i.endDTS*a+this._initDTS,d=1024*s,c=Math.ceil((u-l)/d),f=n.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(h.b.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],v=0;v4294967296;)t+=r;return t}var T=function(t,e,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=i,this.flags=new b(t)},b=function(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}},function(t,e,r){"use strict";r.d(e,"a",(function(){return a}));var i=r(11);function n(t,e){for(var r=0;r0}),!1)}t.exports=function(t,e){e=e||{};var n={main:r.m},o=e.all?{main:Object.keys(n.main)}:function(t,e){for(var r={main:[e]},i={main:[]},n={main:{}};s(r);)for(var o=Object.keys(r),l=0;lt.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},e=t,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Object(n.a)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!==(t=this.fragments)&&void 0!==t&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&h(e.prototype,r),i&&h(e,i),t}(),c=r(17),f=/^(\d+)x(\d+)$/,g=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,v=function(){function t(e){for(var r in"string"==typeof e&&(e=t.parseAttrList(e)),e)e.hasOwnProperty(r)&&(this[r]=e[r])}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=f.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(g.lastIndex=0;null!==(e=g.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function m(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}var y=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,T=/#EXT-X-MEDIA:(.*)/g,b=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),E=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PLAYLIST-TYPE):(.+)/.source,/#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source,/#EXT-X-(SKIP):(.+)/.source,/#EXT-X-(TARGETDURATION): *(\d+)/.source,/#EXT-X-(KEY):(.+)/.source,/#EXT-X-(START):(.+)/.source,/#EXT-X-(ENDLIST)/.source,/#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source,/#EXT-X-(DIS)CONTINUITY/.source,/#EXT-X-(VERSION):(\d+)/.source,/#EXT-X-(MAP):(.+)/.source,/#EXT-X-(SERVER-CONTROL):(.+)/.source,/#EXT-X-(PART-INF):(.+)/.source,/#EXT-X-(GAP)/.source,/#EXT-X-(BITRATE):\s*(\d+)/.source,/#EXT-X-(PART):(.+)/.source,/#EXT-X-(PRELOAD-HINT):(.+)/.source,/#EXT-X-(RENDITION-REPORT):(.+)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),S=/\.(mp4|m4s|m4v|m4a)$/i;var L=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).substr(-4)}return t},t.resolve=function(t,e){return i.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i,n=[],a={},s=!1;for(y.lastIndex=0;null!=(i=y.exec(e));)if(i[1]){var o=new v(i[1]),l={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:t.resolve(i[2],r)},u=o.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),A((o.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=t.convertAVC1ToAVCOTI(l.videoCodec)),n.push(l)}else if(i[3]){var h=new v(i[3]);h["DATA-ID"]&&(s=!0,a[h["DATA-ID"]]=h)}return{levels:n,sessionData:s?a:null}},t.parseMasterPlaylistMedia=function(e,r,i,n){var a;void 0===n&&(n=[]);var s=[],o=0;for(T.lastIndex=0;null!==(a=T.exec(e));){var l=new v(a[1]);if(l.TYPE===i){var u={attrs:l,bitrate:0,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE||"",type:i,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:l.LANGUAGE,url:l.URI?t.resolve(l.URI,r):""};if(n.length){var h=t.findGroup(n,u.groupId)||n[0];R(u,h,"audioCodec"),R(u,h,"textCodec")}s.push(u)}}return s},t.parseLevelPlaylist=function(t,e,r,a,s){var l,h,f,g=new d(e),p=g.fragments,m=null,y=0,T=0,L=0,A=0,R=null,k=new u.b(a,e),_=-1,I=!1;for(b.lastIndex=0,g.m3u8=t;null!==(l=b.exec(t));){I&&(I=!1,(k=new u.b(a,e)).start=L,k.sn=y,k.cc=A,k.level=r,m&&(k.initSegment=m,k.rawProgramDateTime=m.rawProgramDateTime));var C=l[1];if(C){k.duration=parseFloat(C);var w=(" "+l[2]).slice(1);k.title=w||null,k.tagList.push(w?["INF",C,w]:["INF",C])}else if(l[3])Object(n.a)(k.duration)&&(k.start=L,f&&(k.levelkey=f),k.sn=y,k.level=r,k.cc=A,k.urlId=s,p.push(k),k.relurl=(" "+l[3]).slice(1),D(k,R),R=k,L+=k.duration,y++,T=0,I=!0);else if(l[4]){var O=(" "+l[4]).slice(1);R?k.setByteRange(O,R):k.setByteRange(O)}else if(l[5])k.rawProgramDateTime=(" "+l[5]).slice(1),k.tagList.push(["PROGRAM-DATE-TIME",k.rawProgramDateTime]),-1===_&&(_=p.length);else{if(!(l=l[0].match(E))){o.b.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h-1){o.b.warn("Keyformat "+q+" is not supported from the manifest");continue}if("identity"!==q)continue;j&&(f=c.a.fromURL(e,H),H&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(j)>=0&&(f.method=j,f.keyFormat=q,Y&&(f.keyID=Y),W&&(f.keyFormatVersions=W),f.iv=V));break;case"START":var X=new v(P).decimalFloatingPoint("TIME-OFFSET");Object(n.a)(X)&&(g.startTimeOffset=X);break;case"MAP":var z=new v(P);k.relurl=z.URI,z.BYTERANGE&&k.setByteRange(z.BYTERANGE),k.level=r,k.sn="initSegment",f&&(k.levelkey=f),k.initSegment=null,m=k,I=!0;break;case"SERVER-CONTROL":var Q=new v(P);g.canBlockReload=Q.bool("CAN-BLOCK-RELOAD"),g.canSkipUntil=Q.optionalFloat("CAN-SKIP-UNTIL",0),g.canSkipDateRanges=g.canSkipUntil>0&&Q.bool("CAN-SKIP-DATERANGES"),g.partHoldBack=Q.optionalFloat("PART-HOLD-BACK",0),g.holdBack=Q.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var $=new v(P);g.partTarget=$.decimalFloatingPoint("PART-TARGET");break;case"PART":var J=g.partList;J||(J=g.partList=[]);var Z=T>0?J[J.length-1]:void 0,tt=T++,et=new u.c(new v(P),k,e,tt,Z);J.push(et),k.duration+=et.duration;break;case"PRELOAD-HINT":var rt=new v(P);g.preloadHint=rt;break;case"RENDITION-REPORT":var it=new v(P);g.renditionReports=g.renditionReports||[],g.renditionReports.push(it);break;default:o.b.warn("line parsed but not handled: "+l)}}}R&&!R.relurl?(p.pop(),L-=R.duration,g.partList&&(g.fragmentHint=R)):g.partList&&(D(k,R),k.cc=A,g.fragmentHint=k);var nt=p.length,at=p[0],st=p[nt-1];if((L+=g.skippedSegments*g.targetduration)>0&&nt&&st){g.averagetargetduration=L/nt;var ot=st.sn;g.endSN="initSegment"!==ot?ot:0,at&&(g.startCC=at.cc,at.initSegment||g.fragments.every((function(t){return t.relurl&&(e=t.relurl,S.test(null!=(r=null===(n=i.parseURL(e))||void 0===n?void 0:n.path)?r:""));var e,r,n}))&&(o.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(k=new u.b(a,e)).relurl=st.relurl,k.level=r,k.sn="initSegment",at.initSegment=k,g.needSidxRanges=!0))}else g.endSN=0,g.startCC=0;return g.fragmentHint&&(L+=g.fragmentHint.duration),g.totalduration=L,g.endCC=A,_>0&&function(t,e){for(var r=t[e],i=e;i--;){var n=t[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(p,_),g},t}();function A(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return function(t,e){var r=p[e];return!!r&&!0===r[t.slice(0,4)]}(t,r)}));if(i.length){var n=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=n.length>0?n[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function R(t,e,r){var i=e[r];i&&(t[r]=i)}function D(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),Object(n.a)(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}var k=r(4);function _(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}var I=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.hls=t,this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(a.a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(a.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(a.a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(a.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,n=new(r||i)(e);return t.loader=n,this.loaders[t.type]=n,n},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:k.a.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,n=e.url,a=e.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:k.a.LEVEL,url:n,deliveryDirectives:a})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,a=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:k.a.AUDIO_TRACK,url:n,deliveryDirectives:a})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,a=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:k.a.SUBTITLE_TRACK,url:n,deliveryDirectives:a})},e.load=function(t){var e,r,i,n,a,s,l=this.hls.config,u=this.getInternalLoader(t);if(u){var h=u.context;if(h&&h.url===t.url)return void o.b.trace("[playlist-loader]: playlist request ongoing");o.b.log("[playlist-loader]: aborting previous loader for type: "+t.type),u.abort()}switch(t.type){case k.a.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,n=l.manifestLoadingRetryDelay,a=l.manifestLoadingMaxRetryTimeout;break;case k.a.LEVEL:case k.a.AUDIO_TRACK:case k.a.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,n=l.levelLoadingRetryDelay,a=l.levelLoadingMaxRetryTimeout}if((u=this.createInternalLoader(t),null!==(e=t.deliveryDirectives)&&void 0!==e&&e.part)&&(t.type===k.a.LEVEL&&null!==t.level?s=this.hls.levels[t.level].details:t.type===k.a.AUDIO_TRACK&&null!==t.id?s=this.hls.audioTracks[t.id].details:t.type===k.a.SUBTITLE_TRACK&&null!==t.id&&(s=this.hls.subtitleTracks[t.id].details),s)){var d=s.partTarget,c=s.targetduration;d&&c&&(i=Math.min(1e3*Math.max(3*d,.8*c),i))}var f={timeout:i,maxRetry:r,retryDelay:n,maxRetryDelay:a,highWaterMark:0},g={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(t,f,g)},e.loadsuccess=function(t,e,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(t,r),void this.handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),n.indexOf("#EXTINF:")>0||n.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(t,e,r,i):this.handleMasterPlaylist(t,e,r,i)):this.handleManifestParsingError(t,r,"no EXTM3U delimiter",i)},e.loaderror=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!1,t)},e.loadtimeout=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!0)},e.handleMasterPlaylist=function(t,e,r,i){var n=this.hls,s=t.data,l=_(t,r),u=L.parseMasterPlaylist(s,l),h=u.levels,d=u.sessionData;if(h.length){var c=h.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),f=h.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),g=L.parseMasterPlaylistMedia(s,l,"AUDIO",c),p=L.parseMasterPlaylistMedia(s,l,"SUBTITLES",f),m=L.parseMasterPlaylistMedia(s,l,"CLOSED-CAPTIONS");if(g.length)g.some((function(t){return!t.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(o.b.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new v({}),bitrate:0,url:""}));n.trigger(a.a.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,url:l,stats:e,networkDetails:i,sessionData:d})}else this.handleManifestParsingError(t,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function(t,e,r,i){var o=this.hls,l=r.id,u=r.level,h=r.type,d=_(t,r),c=Object(n.a)(l)?l:0,f=Object(n.a)(u)?u:c,g=function(t){switch(t.type){case k.a.AUDIO_TRACK:return k.b.AUDIO;case k.a.SUBTITLE_TRACK:return k.b.SUBTITLE;default:return k.b.MAIN}}(r),p=L.parseLevelPlaylist(t.data,d,f,g,c);if(p.fragments.length){if(h===k.a.MANIFEST){var m={attrs:new v({}),bitrate:0,details:p,name:"",url:d};o.trigger(a.a.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:d,stats:e,networkDetails:i,sessionData:null})}if(e.parsing.end=performance.now(),p.needSidxRanges){var y,T=null===(y=p.fragments[0].initSegment)||void 0===y?void 0:y.url;this.load({url:T,isSidxRequest:!0,type:h,level:u,levelDetails:p,id:l,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=p,this.handlePlaylistLoaded(t,e,r,i)}else o.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.LEVEL_EMPTY_ERROR,fatal:!1,url:d,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function(t,e){var r=Object(l.g)(new Uint8Array(t.data));if(r){var i=r.references,n=e.levelDetails;i.forEach((function(t,e){var i=t.info,a=n.fragments[e];0===a.byteRange.length&&a.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),a.initSegment&&a.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}))}},e.handleManifestParsingError=function(t,e,r,i){this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:e.type===k.a.MANIFEST,url:t.url,reason:r,response:t,context:e,networkDetails:i})},e.handleNetworkError=function(t,e,r,i){void 0===r&&(r=!1),o.b.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+t.type+" level: "+t.level+" id: "+t.id+' group-id: "'+t.groupId+'"');var n=s.a.UNKNOWN,l=!1,u=this.getInternalLoader(t);switch(t.type){case k.a.MANIFEST:n=r?s.a.MANIFEST_LOAD_TIMEOUT:s.a.MANIFEST_LOAD_ERROR,l=!0;break;case k.a.LEVEL:n=r?s.a.LEVEL_LOAD_TIMEOUT:s.a.LEVEL_LOAD_ERROR,l=!1;break;case k.a.AUDIO_TRACK:n=r?s.a.AUDIO_TRACK_LOAD_TIMEOUT:s.a.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case k.a.SUBTITLE_TRACK:n=r?s.a.SUBTITLE_TRACK_LOAD_TIMEOUT:s.a.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(t.type);var h={type:s.b.NETWORK_ERROR,details:n,fatal:l,url:t.url,loader:u,context:t,networkDetails:e};i&&(h.response=i),this.hls.trigger(a.a.ERROR,h)},e.handlePlaylistLoaded=function(t,e,r,i){var n=r.type,s=r.level,o=r.id,l=r.groupId,u=r.loader,h=r.levelDetails,d=r.deliveryDirectives;if(null!=h&&h.targetduration){if(u)switch(h.live&&(u.getCacheAge&&(h.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(h.ageHeader)||(h.ageHeader=0)),n){case k.a.MANIFEST:case k.a.LEVEL:this.hls.trigger(a.a.LEVEL_LOADED,{details:h,level:s||0,id:o||0,stats:e,networkDetails:i,deliveryDirectives:d});break;case k.a.AUDIO_TRACK:this.hls.trigger(a.a.AUDIO_TRACK_LOADED,{details:h,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:d});break;case k.a.SUBTITLE_TRACK:this.hls.trigger(a.a.SUBTITLE_TRACK_LOADED,{details:h,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:d})}}else this.handleManifestParsingError(t,r,"invalid target duration",i)},t}(),C=function(){function t(t){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){this.hls.on(a.a.KEY_LOADING,this.onKeyLoading,this)},e._unregisterListeners=function(){this.hls.off(a.a.KEY_LOADING,this.onKeyLoading)},e.destroy=function(){for(var t in this._unregisterListeners(),this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={}},e.onKeyLoading=function(t,e){var r=e.frag,i=r.type,n=this.loaders[i];if(r.decryptdata){var s=r.decryptdata.uri;if(s!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(n&&(o.b.warn("abort previous key loader for type:"+i),n.abort()),!s)return void o.b.warn("key uri is falsy");var u=l.loader,h=r.loader=this.loaders[i]=new u(l);this.decrypturl=s,this.decryptkey=null;var d={url:s,frag:r,responseType:"arraybuffer"},c={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};h.load(d,c,f)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(a.a.KEY_LOADED,{frag:r}))}else o.b.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function(t,e,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(t.data),i.loader=null,delete this.loaders[i.type],this.hls.trigger(a.a.KEY_LOADED,{frag:i})):o.b.error("after key load, decryptdata unset")},e.loaderror=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.loadtimeout=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(a.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}();function w(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function O(t,e){var r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(r){o.b.debug("[texttrack-utils]: "+r);var i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}"disabled"===r&&(t.mode=r)}function x(t){var e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(var r=t.cues.length;r--;)t.removeCue(t.cues[r]);"disabled"===e&&(t.mode=e)}function P(t,e,r){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var n=function(t,e,r){var i=[],n=function(t,e){if(et[r].endTime)return-1;var i=0,n=r;for(;i<=n;){var a=Math.floor((n+i)/2);if(et[a].startTime&&i-1)for(var a=n,s=t.length;a=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),a=0;a.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(u,Math.max(1,h))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},n.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},n.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},e=t,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var h=i;return u+Math.min(1*this.stallCount,h)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,n=t-e-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return r?t.buffered.end(r-1):e.edge-this.currentTime}}])&&N(e.prototype,r),i&&N(e,i),t}();function G(t,e){for(var r=0;rt.sn?(a=r-t.start,i=t):(a=t.start-r,i=e),i.duration!==a&&(i.duration=a)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function Y(t,e,r,i,a,s){i-r<=0&&(o.b.warn("Fragment should have a positive duration",e),i=r+e.duration,s=a+e.duration);var l=r,u=i,h=e.startPTS,d=e.endPTS;if(Object(n.a)(h)){var c=Math.abs(h-r);Object(n.a)(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,l=Math.max(r,h),r=Math.min(r,h),a=Math.min(a,e.startDTS),u=Math.min(i,d),i=Math.max(i,d),s=Math.max(s,e.endDTS)}e.duration=i-r;var f=r-e.start;e.appendedPTS=i,e.start=e.startPTS=r,e.maxStartPTS=l,e.startDTS=a,e.endPTS=i,e.minEndPTS=u,e.endDTS=s;var g,v=e.sn;if(!t||vt.endSN)return 0;var p=v-t.startSN,m=t.fragments;for(m[p]=e,g=p;g>0;g--)W(m[g],m[g-1]);for(g=p;g=0;a--){var s=i[a].initSegment;if(s){r=s;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var l,u=0;(function(t,e,r){for(var i=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,s=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=n;u<=a;u++){var h=l[s+u],d=o[u];i&&!d&&u=i.length||z(e,i[r].start)}function z(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;ie.partTarget&&(l+=1)}if(Object(n.a)(o))return new K(o,Object(n.a)(l)?l:void 0,U.No)}}},e.loadPlaylist=function(t){},e.shouldLoadTrack=function(t){return this.canLoad&&t&&!!t.url&&(!t.details||t.details.live)},e.playlistLoaded=function(t,e,r){var i=this,n=e.details,a=e.stats,s=a.loading.end?Math.max(0,self.performance.now()-a.loading.end):0;if(n.advancedDateTime=Date.now()-s,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log("live playlist "+t+" "+(n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:"MISSED")),r&&n.fragments.length>0&&q(r,n),!this.canLoad||!n.live)return;var o,l=void 0,u=void 0;if(n.canBlockReload&&n.endSN&&n.advanced){var h=this.hls.config.lowLatencyMode,d=n.lastPartSn,c=n.endSN,f=n.lastPartIndex,g=d===c;-1!==f?(l=g?c+1:d,u=g?h?0:f:f+1):l=c+1;var v=n.age,p=v+n.ageHeader,m=Math.min(p-n.partTarget,1.5*n.targetduration);if(m>0){if(r&&m>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+m+" with playlist age: "+n.age),m=0;else{var y=Math.floor(m/n.targetduration);if(l+=y,void 0!==u)u+=Math.round(m%n.targetduration/n.partTarget);this.log("CDN Tune-in age: "+n.ageHeader+"s last advanced "+v.toFixed(2)+"s goal: "+m+" skip sn "+y+" to part "+u)}n.tuneInGoal=m}if(o=this.getDeliveryDirectives(n,e.deliveryDirectives,l,u),h||!g)return void this.loadPlaylist(o)}else o=this.getDeliveryDirectives(n,e.deliveryDirectives,l,u);var T=function(t,e){var r,i=1e3*t.levelTargetDuration,n=i/2,a=t.age,s=a>0&&a<3*i,o=e.loading.end-e.loading.start,l=t.availabilityDelay;if(!1===t.updated)if(s){var u=333*t.misses;r=Math.max(Math.min(n,2*o),u),t.availabilityDelay=(t.availabilityDelay||0)+r}else r=n;else s?(l=Math.min(l||i/2,a),t.availabilityDelay=l,r=l+i-a):r=i-o;return Math.round(r)}(n,a);void 0!==l&&n.canBlockReload&&(T-=n.partTarget||1),this.log("reload live playlist "+t+" in "+Math.round(T)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(o)}),T)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,r,i){var n=function(t,e){var r=t.canSkipUntil,i=t.canSkipDateRanges,n=t.endSN;return r&&(void 0!==e?e-n:0)-1&&null!==(e=t.context)&&void 0!==e&&e.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+t.details+'"'),this.loadPlaylist();else{var a=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),a),this.warn("retry playlist loading #"+this.retryCount+" in "+a+' ms after "'+t.details+'"')}else this.warn('cannot recover from error "'+t.details+'"'),this.clearTimer(),t.fatal=!0;return n},t}();function $(){return($=Object.assign||function(t){for(var e=1;e0){r=n[0].bitrate,n.sort((function(t,e){return t.bitrate-e.bitrate})),this._levels=n;for(var f=0;fthis.hls.config.fragLoadingMaxRetry&&(a=r.frag.level)):a=r.frag.level}break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),a=i.level),o=!0;break;case s.a.REMUX_ALLOC_ERROR:a=r.level,o=!0}void 0!==a&&this.recoverLevel(r,a,o,l)}}},u.recoverLevel=function(t,e,r,i){var n=t.details,a=this._levels[e];if(a.loadError++,r){if(!this.retryLoadingOrFail(t))return void(this.currentLevelIndex=-1);t.levelRetry=!0}if(i){var s=a.url.length;if(s>1&&a.loadError1){var i=(e.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(t){t.urlId=i})),this.level=t}},u.onFragLoaded=function(t,e){var r=e.frag;if(void 0!==r&&r.type===k.b.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},u.onLevelLoaded=function(t,e){var r,i,n=e.level,a=e.details,s=this._levels[n];if(!s)return this.warn("Invalid level index "+n),void(null!==(i=e.deliveryDirectives)&&void 0!==i&&i.skip&&(a.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(n,e,s.details)):null!==(r=e.deliveryDirectives)&&void 0!==r&&r.skip&&(a.deltaUpdateFailed=!0)},u.onAudioTrackSwitched=function(t,e){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,n=this.hls.audioTracks[e.id].groupId,a=0;a0){var i=r.urlId,n=r.url[i];if(t)try{n=t.addDirectives(n)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Attempt loading level index "+e+(t?" at sn "+t.msn+" part "+t.part:"")+" with URL-id "+i+" "+n),this.clearTimer(),this.hls.trigger(a.a.LEVEL_LOADING,{url:n,level:e,id:i,deliveryDirectives:t||null})}},u.removeLevel=function(t,e){var r=function(t,r){return r!==e},i=this._levels.filter((function(i,n){return n!==t||i.url.length>1&&void 0!==e&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(t,e){var r=t.details;return null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e})),t}));this._levels=i,this.hls.trigger(a.a.LEVELS_UPDATED,{levels:i})},n=i,(o=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==t||null===(e=r[t])||void 0===e||!e.details)){if(t<0||t>=r.length){var i=t<0;if(this.hls.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:t,fatal:i,reason:"invalid level idx"}),i)return;t=Math.min(t,r.length-1)}this.clearTimer();var n=this.currentLevelIndex,o=r[n],l=r[t];this.log("switching to level "+t+" from "+n),this.currentLevelIndex=t;var u=$({},l,{level:t,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(a.a.LEVEL_SWITCHING,u);var h=l.details;if(!h||h.live){var d=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(d)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])&&J(n.prototype,o),l&&J(n,l),i}(Q);!function(t){t.NOT_LOADED="NOT_LOADED",t.BACKTRACKED="BACKTRACKED",t.APPENDING="APPENDING",t.PARTIAL="PARTIAL",t.OK="OK"}(tt||(tt={}));var it=function(){function t(t){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(a.a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.a.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(a.a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.a.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){if(e===k.b.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var n=i.length;n--;){var a=i[n],s=a?a.end:r.appendedPTS;if(a.start<=t&&void 0!==s&&t<=s)return n>9&&(this.activeParts=i.slice(n-9)),a}else if(r.start<=t&&void 0!==r.appendedPTS&&t<=r.appendedPTS)return r}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),n=i.length;n--;){var a=r[i[n]];if((null==a?void 0:a.body.type)===e&&a.buffered){var s=a.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e,r){var i=this;Object.keys(this.fragments).forEach((function(n){var a=i.fragments[n];if(a)if(a.buffered){var s=a.range[t];s&&s.time.some((function(t){var r=!i.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&i.removeFragment(a.body),r}))}else a.body.type===r&&i.removeFragment(a.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,n=t.part;if(r&&"initSegment"!==i.sn){var a=at(i),s=this.fragments[a];s&&(Object.keys(r).forEach((function(t){var a=i.elementaryStreams[t];if(a){var o=r[t],l=null!==n||!0===a.partial;s.range[t]=e.getBufferedTimes(i,n,l,o)}})),s.backtrack=s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},e.fragBuffered=function(t){var e=at(t),r=this.fragments[e];r&&(r.backtrack=r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var n={time:[],partial:r},a=e?e.start:t.start,s=e?e.end:t.end,o=t.minEndPTS||s,l=t.maxStartPTS||a,u=0;u=h&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(ah)n.partial=!0,n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=h)break}return n},e.getPartialFragment=function(t){var e,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&nt(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),a<=e&&(n=u.body,a=e)))})),n},e.getState=function(t){var e=at(t),r=this.fragments[e];return r?r.buffered?nt(r)?tt.PARTIAL:tt.OK:r.backtrack?tt.BACKTRACKED:tt.APPENDING:tt.NOT_LOADED},e.backtrack=function(t,e){var r=at(t),i=this.fragments[r];if(!i||i.backtrack)return null;var n=i.backtrack=e||i.loaded;return i.loaded=null,n},e.getBacktrackData=function(t){var e=at(t),r=this.fragments[e];if(r){var i,n=r.backtrack;if(null!=n&&null!==(i=n.payload)&&void 0!==i&&i.byteLength)return n;this.removeFragment(t)}return null},e.isTimeBuffered=function(t,e,r){for(var i,n,a=0;a=i&&e<=n)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var n=at(r);this.fragments[n]={body:r,loaded:e,backtrack:null,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,n=e.part,a=e.timeRanges;if(i.type===k.b.MAIN)if(this.activeFragment=i,n){var s=this.activeParts;s||(this.activeParts=s=[]),s.push(n)}else this.activeParts=null;this.timeRanges=a,Object.keys(a).forEach((function(t){var e=a[t];if(r.detectEvictedFragments(t,e),!n)for(var s=0;st&&i.removeFragment(s)}}))},e.removeFragment=function(t){var e=at(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),delete this.fragments[e]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},t}();function nt(t){var e,r;return t.buffered&&((null===(e=t.range.video)||void 0===e?void 0:e.partial)||(null===(r=t.range.audio)||void 0===r?void 0:r.partial))}function at(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn}var st=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),ot={length:0,start:function(){return 0},end:function(){return 0}},lt=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),n=0;n=i.start(n)&&r<=i.end(n))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var n,a=t.getBuffered(e),s=[];for(n=0;ns&&(i[a-1].end=t[n].end):i.push(t[n])}else i.push(t[n])}else i=t;for(var o,l=0,u=e,h=e,d=0;d=c&&er.startCC||t&&t.cc0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null}};function pt(t,e,r,i){void 0===r&&(r=0),void 0===i&&(i=0);var n=null;if(t?n=e[t.sn-e[0].sn+1]||null:0===r&&0===e[0].start&&(n=e[0]),n&&0===mt(r,i,n))return n;var a=vt.search(e,mt.bind(null,r,i));return a||n}function mt(t,e,r){void 0===t&&(t=0),void 0===e&&(e=0);var i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function yt(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function Tt(t){var e="function"==typeof Map?new Map:void 0;return(Tt=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return bt(t,arguments,Lt(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),St(i,t)})(t)}function bt(t,e,r){return(bt=Et()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var n=new(Function.bind.apply(t,i));return r&&St(n,r.prototype),n}).apply(null,arguments)}function Et(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function St(t,e){return(St=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Lt(t){return(Lt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var At=Math.pow(2,17),Rt=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,i=t.url;if(!i)return Promise.reject(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var n=this.config,a=n.fLoader,o=n.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var u=r.loader=t.loader=a?new a(n):new o(n),h=Dt(t),d={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout,highWaterMark:At};t.stats=u.stats,u.load(h,d,{onSuccess:function(e,n,a,s){r.resetLoader(t,u),i({frag:t,part:null,payload:e.data,networkDetails:s})},onError:function(e,i,n){r.resetLoader(t,u),l(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:e,networkDetails:n}))},onAbort:function(e,i,n){r.resetLoader(t,u),l(new kt({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,networkDetails:n}))},onTimeout:function(e,i,n){r.resetLoader(t,u),l(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,networkDetails:n}))},onProgress:function(r,i,n,a){e&&e({frag:t,part:null,payload:n,networkDetails:a})}})}))},e.loadPart=function(t,e,r){var i=this;this.abort();var n=this.config,a=n.fLoader,o=n.loader;return new Promise((function(l,u){i.loader&&i.loader.destroy();var h=i.loader=t.loader=a?new a(n):new o(n),d=Dt(t,e),c={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout,highWaterMark:At};e.stats=h.stats,h.load(d,c,{onSuccess:function(n,a,s,o){i.resetLoader(t,h),i.updateStatsFromPart(t,e);var u={frag:t,part:e,payload:n.data,networkDetails:o};r(u),l(u)},onError:function(r,n,a){i.resetLoader(t,h),u(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r,networkDetails:a}))},onAbort:function(r,n,a){t.stats.aborted=e.stats.aborted,i.resetLoader(t,h),u(new kt({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,networkDetails:a}))},onTimeout:function(r,n,a){i.resetLoader(t,h),u(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,networkDetails:a}))}})}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(t.duration/e.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function Dt(t,e){void 0===e&&(e=null);var r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return Object(n.a)(a)&&Object(n.a)(s)&&(i.rangeStart=a,i.rangeEnd=s),i}var kt=function(t){var e,r;function i(e){for(var r,i=arguments.length,n=new Array(i>1?i-1:0),a=1;a=e.endSN&&!t.nextStart){var n=e.partList;if(null!=n&&n.length){var a=n[n.length-1];return lt.isBuffered(this.media,a.start+a.duration/2)}var s=i.getState(r);return s===tt.PARTIAL||s===tt.OK}return!1},c.onMediaAttached=function(t,e){var r=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);var i=this.config;this.levels&&i.autoStartLoad&&this.state===Ot&&this.startLoad(i.startPosition)},c.onMediaDetaching=function(){var t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},c.onMediaSeeking=function(){var t=this.config,e=this.fragCurrent,r=this.media,i=this.mediaBuffer,a=this.state,s=r?r.currentTime:0,o=lt.bufferInfo(i||r,s,t.maxBufferHole);if(this.log("media seeking to "+(Object(n.a)(s)?s.toFixed(3):s)+", state: "+a),a===Kt)this.resetLoadingState();else if(e&&!o.len){var l=t.maxFragLookUpTolerance,u=e.start-l,h=s>e.start+e.duration+l;(s0&&s&&s.key&&s.iv&&"AES-128"===s.method){var o=self.performance.now();return e.decrypter.webCryptoDecrypt(new Uint8Array(n),s.key.buffer,s.iv.buffer).then((function(e){var n=self.performance.now();return i.trigger(a.a.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:o,tdecrypt:n}}),r.payload=e,r}))}return r})).then((function(r){var i=e.fragCurrent,n=e.hls,s=e.levels;if(!s)throw new Error("init load aborted, missing levels");s[t.level].details;var o=t.stats;e.state=xt,e.fragLoadError=0,t.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&n.trigger(a.a.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:t.type}),e.tick()})).catch((function(r){e.warn(r),e.resetFragmentLoading(t)}))},c.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},c.fragBufferedComplete=function(t,e){var r=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level+" "+It.toString(lt.getBuffered(r))),this.state=xt,this.tick()},c._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,n=t.partsLoaded,a=!n||0===n.length||n.some((function(t){return!t})),s=new ut(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);e.flush(s)}},c._handleFragmentLoadProgress=function(t){},c._doFragLoad=function(t,e,r,i){var s=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(t.start,r||0),this.config.lowLatencyMode&&e){var o=e.partList;if(o&&i){r>t.end&&e.fragmentHint&&(t=e.fragmentHint);var l=this.getNextPart(o,t,r);if(l>-1){var u=o[l];return this.log("Loading part sn: "+t.sn+" p: "+u.index+" cc: "+t.cc+" of playlist ["+e.startSN+"-"+e.endSN+"] parts [0-"+l+"-"+(o.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=Mt,this.hls.trigger(a.a.FRAG_LOADING,{frag:t,part:o[l],targetBufferTime:r}),this.doFragPartsLoad(t,o,l,i).catch((function(t){return s.handleFragLoadError(t)}))}if(!t.url||this.loadedEndOfParts(o,r))return Promise.resolve(null)}}return this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(e?"of ["+e.startSN+"-"+e.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),Object(n.a)(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Mt,this.hls.trigger(a.a.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragmentLoader.load(t,i).catch((function(t){return s.handleFragLoadError(t)}))},c.doFragPartsLoad=function(t,e,r,i){var n=this;return new Promise((function(s,o){var l=[];!function r(u){var h=e[u];n.fragmentLoader.loadPart(t,h,i).then((function(i){l[h.index]=i;var o=i.part;n.hls.trigger(a.a.FRAG_LOADED,i);var d=e[u+1];if(!d||d.fragment!==t)return s({frag:t,part:o,partsLoaded:l});r(u+1)})).catch(o)}(r)}))},c.handleFragLoadError=function(t){var e=t.data;return e&&e.details===s.a.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(a.a.ERROR,e),null},c._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===Ut){var r=e.frag,i=e.part,n=e.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(r,i,n,t.partial)}else this.fragCurrent||(this.state=xt)},c.getCurrentContext=function(t){var e=this.levels,r=t.level,i=t.sn,n=t.part;if(!e||!e[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var a=e[r],s=n>-1?function(t,e,r){if(!t||!t.details)return null;var i=t.details.partList;if(i)for(var n=i.length;n--;){var a=i[n];if(a.index===r&&a.fragment.sn===e)return a}return null}(a,i,n):null,o=s?s.fragment:function(t,e,r){if(!t||!t.details)return null;var i=t.details,n=i.fragments[e-i.startSN];return n||((n=i.fragmentHint)&&n.sn===e?n:ea&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},c.getFwdBufferInfo=function(t,e){var r=this.config,i=this.getLoadPosition();if(!Object(n.a)(i))return null;var a=lt.bufferInfo(t,i,r.maxBufferHole);if(0===a.len&&void 0!==a.nextStart){var s=this.fragmentTracker.getBufferedFrag(i,e);if(s&&a.nextStart=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},c.getNextFragment=function(t,e){var r,i,n=e.fragments,a=n.length;if(!a)return null;var s,o=this.config,l=n[0].start;if(e.live){var u=o.initialLiveManifestSize;if(a-1&&rr.start&&r.loaded},c.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!Object(n.a)(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=t.startSN&&a<=t.endSN){var s=e[a-t.startSN];r.cc===s.cc&&(i=s,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return vt.search(t,(function(t){return t.cce?-1:0}))}(e,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var o=this.hls.liveSyncPosition;null!==o&&(i=this.getFragmentAtPosition(o,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},c.getFragmentAtPosition=function(t,e,r){var i,n=this.config,a=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=n.maxFragLookUpTolerance,h=!!(n.lowLatencyMode&&r.partList&&l);(h&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),te-u?0:u):i=s[s.length-1];if(i){var d=i.sn-r.startSN,c=a&&i.level===a.level,f=s[d+1];if(this.fragmentTracker.getState(i)===tt.BACKTRACKED){i=null;for(var g=d;s[g]&&this.fragmentTracker.getState(s[g])===tt.BACKTRACKED;)i=a?s[g--]:s[--g];i||(i=f)}else a&&i.sn===a.sn&&!h&&c&&(i.sn=a-e.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n"+t.startSN+" prev-sn: "+(a?a.sn:"na")+" fragments: "+o),d}return l},c.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},c.setStartPosition=function(t,e){var r=this.startPosition;if(r"+t))}}])&&Ct(u.prototype,h),d&&Ct(u,d),i}(st);function Yt(){return self.MediaSource||self.WebKitMediaSource}function qt(){return self.SourceBuffer||self.WebKitSourceBuffer}var Xt=r(18),zt=r(10),Qt=r(14),$t=Yt()||{isTypeSupported:function(){return!1}},Jt=function(){function t(t,e,r,i){var n=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.hls=t,this.id=e,this.onTransmuxComplete=r,this.onFlush=i;var l=t.config,u=function(e,r){(r=r||{}).frag=n.frag,r.id=n.id,t.trigger(e,r)};this.observer=new Qt.EventEmitter,this.observer.on(a.a.FRAG_DECRYPTED,u),this.observer.on(a.a.ERROR,u);var h={mp4:$t.isTypeSupported("video/mp4"),mpeg:$t.isTypeSupported("audio/mpeg"),mp3:$t.isTypeSupported('audio/mp4; codecs="mp3"')},d=navigator.vendor;if(l.enableWorker&&"undefined"!=typeof Worker){var c;o.b.log("demuxing in webworker");try{c=this.worker=Xt(19),this.onwmsg=this.onWorkerMessage.bind(this),c.addEventListener("message",this.onwmsg),c.onerror=function(e){t.trigger(a.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",error:new Error(e.message+" ("+e.filename+":"+e.lineno+")")})},c.postMessage({cmd:"init",typeSupported:h,vendor:d,id:e,config:JSON.stringify(l)})}catch(t){o.b.warn("Error in worker:",t),o.b.error("Error while initializing DemuxerWorker, fallback to inline"),c&&self.URL.revokeObjectURL(c.objectURL),this.transmuxer=new zt.c(this.observer,h,l,d,e),this.worker=null}}else this.transmuxer=new zt.c(this.observer,h,l,d,e)}var e=t.prototype;return e.destroy=function(){var t=this.worker;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.worker=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.observer=null},e.push=function(t,e,r,i,n,a,s,l,u,h){var d,c,f=this;u.transmuxing.start=self.performance.now();var g=this.transmuxer,v=this.worker,p=a?a.start:n.start,m=n.decryptdata,y=this.frag,T=!(y&&n.cc===y.cc),b=!(y&&u.level===y.level),E=y?u.sn-y.sn:-1,S=this.part?u.part-this.part.index:1,L=!b&&(1===E||0===E&&1===S),A=self.performance.now();(b||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=A),!a||!S&&L||(a.stats.parsing.start=A);var R=!(y&&(null===(d=n.initSegment)||void 0===d?void 0:d.url)===(null===(c=y.initSegment)||void 0===c?void 0:c.url)),D=new zt.b(T,L,l,b,p,R);if(!L||T||R){o.b.log("[transmuxer-interface, "+n.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+T+"\n trackSwitch: "+b+"\n contiguous: "+L+"\n accurateTimeOffset: "+l+"\n timeOffset: "+p+"\n initSegmentChange: "+R);var k=new zt.a(r,i,e,s,h);this.configureTransmuxer(k)}if(this.frag=n,this.part=a,v)v.postMessage({cmd:"demux",data:t,decryptdata:m,chunkMeta:u,state:D},t instanceof ArrayBuffer?[t]:[]);else if(g){var _=g.push(t,m,u,D);Object(zt.d)(_)?_.then((function(t){f.handleTransmuxComplete(t)})):this.handleTransmuxComplete(_)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:t});else if(r){var n=r.flush(t);Object(zt.d)(n)?n.then((function(r){e.handleFlushResult(r,t)})):this.handleFlushResult(n,t)}},e.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},e.configureTransmuxer=function(t){var e=this.worker,r=this.transmuxer;e?e.postMessage({cmd:"configure",config:t}):r&&r.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}(),Zt=function(){function t(t,e,r,i){this.config=void 0,this.media=void 0,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.hls=this.fragmentTracker=this.media=null},e.poll=function(t){var e=this.config,r=this.media,i=this.stalled,n=r.currentTime,a=r.seeking,s=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n===t){if((l||s)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&<.getBuffered(r).length){var u=lt.bufferInfo(r,n,0),h=u.len>0,d=u.nextStart||0;if(h||d){if(a){var c=u.len>2,f=!d||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(c||f)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var g,v=Math.max(d,u.start||0)-n,p=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==p||null===(g=p.details)||void 0===g?void 0:g.live)?2*p.details.targetduration:2;if(v>0&&v<=m)return void this._trySkipBufferHole(null)}var y=self.performance.now();if(null!==i){var T=y-i;!a&&T>=250&&this._reportStall(u.len);var b=lt.bufferInfo(r,n,e.maxBufferHole);this._tryFixBufferStall(b,T)}else this.stalled=y}}}else if(this.moved=!0,null!==i){if(this.stallReported){var E=self.performance.now()-i;o.b.warn("playback not stuck anymore @"+n+", after "+Math.round(E)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,n=this.media.currentTime,a=i.getPartialFragment(n);if(a&&this._trySkipBufferHole(a))return;t.len>r.maxBufferHole&&e>1e3*r.highBufferWatchdogPeriod&&(o.b.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},e._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,o.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+t+")"),e.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e._trySkipBufferHole=function(t){for(var e=this.config,r=this.hls,i=this.media,n=i.currentTime,l=0,u=lt.getBuffered(i),h=0;h=l&&n0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=xt,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Ot},c.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},c.doTick=function(){switch(this.state){case xt:this.doTickIdle();break;case Vt:var t,e=this.levels,r=this.level,i=null==e||null===(t=e[r])||void 0===t?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=xt;break}break;case Ft:var n,a=self.performance.now(),s=this.retryDate;(!s||a>=s||null!==(n=this.media)&&void 0!==n&&n.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=xt)}this.onTickEnd()},c.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},c.doTickIdle=function(){var t,e,r=this.hls,i=this.levelLastLoaded,n=this.levels,s=this.media,o=r.config,l=r.nextLoadLevel;if(null!==i&&(s||!this.startFragRequested&&o.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&n&&n[l]){var h=n[l];this.level=r.nextLoadLevel=l;var d=h.details;if(!d||this.state===Vt||d.live&&this.levelLastLoaded!==l)this.state=Vt;else{var c=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:s,k.b.MAIN);if(null!==c)if(!(c.len>=this.getMaxBufferLength(h.maxBitrate))){if(this._streamEnded(c,d)){var f={};return this.altAudio&&(f.type="video"),this.hls.trigger(a.a.BUFFER_EOS,f),void(this.state=Kt)}var g=c.end,v=this.getNextFragment(g,d);if(this.couldBacktrack&&!this.fragPrevious&&v&&"initSegment"!==v.sn){var p=v.sn-d.startSN;p>1&&(v=d.fragments[p-1],this.fragmentTracker.removeFragment(v))}if(v&&this.fragmentTracker.getState(v)===tt.OK&&this.nextLoadPosition>g){var m=this.audioOnly&&!this.altAudio?u.a.AUDIO:u.a.VIDEO;this.afterBufferFlushed(s,m,k.b.MAIN),v=this.getNextFragment(this.nextLoadPosition,d)}v&&(!v.initSegment||v.initSegment.data||this.bitrateTest||(v=v.initSegment),"identity"!==(null===(t=v.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=v.decryptdata)&&void 0!==e&&e.key?this.loadFragment(v,d,g):this.loadKey(v,d))}}}},c.loadFragment=function(e,r,i){var n,a=this.fragmentTracker.getState(e);if(this.fragCurrent=e,a===tt.BACKTRACKED){var s=this.fragmentTracker.getBacktrackData(e);if(s)return this._handleFragmentLoadProgress(s),void this._handleFragmentLoadComplete(s);a=tt.NOT_LOADED}a===tt.NOT_LOADED||a===tt.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e):this.bitrateTest?(e.bitrateTest=!0,this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):a===tt.APPENDING?this.reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e):0===(null===(n=this.media)||void 0===n?void 0:n.buffered.length)&&this.fragmentTracker.removeAllFragments()},c.getAppendedFrag=function(t){var e=this.fragmentTracker.getAppendedFrag(t,k.b.MAIN);return e&&"fragment"in e?e.fragment:e},c.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,k.b.MAIN)},c.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},c.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},c.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!e.paused&&t){var n=t[this.hls.nextLoadLevel],a=this.fragLastKbps;r=a&&this.fragCurrent?this.fragCurrent.duration*n.maxBitrate/(1e3*a)+1:0}else r=0;var s=this.getBufferedFrag(e.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,h=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}},c.abortCurrentFrag=function(){var t=this.fragCurrent;this.fragCurrent=null,null!=t&&t.loader&&t.loader.abort(),this.state===Pt&&(this.state=xt),this.nextLoadPosition=this.getLoadPosition()},c.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},c.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Zt(this.config,i,this.fragmentTracker,this.hls)},c.onMediaDetaching=function(){var e=this.media;e&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},c.onMediaPlaying=function(){this.tick()},c.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;Object(n.a)(e)&&this.log("Media seeked to "+e.toFixed(3)),this.tick()},c.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(a.a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},c.onManifestParsed=function(t,e){var r,i,n,a=!1,s=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(a=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=a&&s&&!("function"==typeof(null==(n=qt())||null===(i=n.prototype)||void 0===i?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},c.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===xt){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=Vt)}},c.onLevelLoaded=function(t,e){var r,i=this.levels,n=e.level,s=e.details,o=s.totalduration;if(i){this.log("Level "+n+" loaded ["+s.startSN+","+s.endSN+"], cc ["+s.startCC+", "+s.endCC+"] duration:"+o);var l=this.fragCurrent;!l||this.state!==Mt&&this.state!==Ft||l.level!==e.level&&l.loader&&(this.state=xt,l.loader.abort());var u=i[n],h=0;if(s.live||null!==(r=u.details)&&void 0!==r&&r.live){if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed)return;h=this.alignPlaylists(s,u.details)}if(u.details=s,this.levelLastLoaded=n,this.hls.trigger(a.a.LEVEL_UPDATED,{details:s,level:n}),this.state===Vt){if(this.waitForCdnTuneIn(s))return;this.state=xt}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,h),this.tick()}else this.warn("Levels were reset while loading level "+n)},c._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,n=t.payload,a=this.levels;if(a){var s=a[r.level],o=s.details;if(o){var l=s.videoCodec,u=o.PTSKnown||!o.live,h=null===(e=r.initSegment)||void 0===e?void 0:e.data,d=this._getAudioCodec(s),c=this.transmuxer=this.transmuxer||new Jt(this.hls,k.b.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,v=new ut(r.level,r.sn,r.stats.chunkCount,n.byteLength,f,g),p=this.initPTS[r.cc];c.push(n,h,d,l,r,i,o.totalduration,u,v,p)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},c.onAudioTrackSwitching=function(t,e){var r=this.altAudio,i=!!e.url,n=e.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;null!=s&&s.loader&&(this.log("Switching to main audio track, cancel main fragment load"),s.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:n})}},c.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i,this.tick()},c.onBufferCreated=function(t,e){var r,i,n=e.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},c.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===k.b.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Bt&&(this.state=xt));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},c.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(k.b.MAIN,e);break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==jt&&(e.fatal?(this.warn(""+e.details),this.state=jt):e.levelRetry||this.state!==Vt||(this.state=xt));break;case s.a.BUFFER_FULL_ERROR:if("main"===e.parent&&(this.state===Ut||this.state===Bt)){var r=!0,i=this.getFwdBufferInfo(this.media,k.b.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},c.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){var r=lt.getBuffered(t);!this.loadedmetadata&&r.length?(this.loadedmetadata=!0,this.seekToStartPos()):e.poll(this.lastCurrentTime),this.lastCurrentTime=t.currentTime}},c.onFragLoadEmergencyAborted=function(){this.state=xt,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},c.onBufferFlushed=function(t,e){var r=e.type;if(r!==u.a.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.a.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,k.b.MAIN)}},c.onLevelsUpdated=function(t,e){this.levels=e.levels},c.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},c.seekToStartPos=function(){var t=this.media,e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&(n1&&!1===t.seeking){var r=t.currentTime;if(lt.isBuffered(t,r)?e=this.getAppendedFrag(r):lt.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){var i=this.fragPlaying,n=e.level;i&&e.sn===i.sn&&i.level===n&&e.urlId===i.urlId||(this.hls.trigger(a.a.FRAG_CHANGED,{frag:e}),i&&i.level===n||this.hls.trigger(a.a.LEVEL_SWITCHED,{level:n}),this.fragPlaying=e)}}},l=i,(h=[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentLevel",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);if(e)return e.level}return-1}},{key:"nextBufferedFrag",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);return this.followingBufferedFrag(e)}return null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&te(l.prototype,h),d&&te(l,d),i}(Wt),ie=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),ne=function(){function t(t,e,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ie(t),this.fast_=new ie(e)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_;this.slow_.halfLife!==t&&(this.slow_=new ie(t,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==e&&(this.fast_=new ie(e,i.getEstimate(),i.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function(){},t}();function ae(t,e){for(var r=0;r=2*h/c||y<=b)){var E,S=Number.POSITIVE_INFINITY;for(E=t.level-1;E>g;E--){if((S=h*f[E].maxBitrate/(6.4*m))=y)){var L=this.bwEstimator.getEstimate();o.b.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+E+"\n Current BW estimate: "+(Object(n.a)(L)?(L/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+y.toFixed(3)+" s\n Estimated load time for the next fragment: "+S.toFixed(3)+" s\n Time to underbuffer: "+b.toFixed(3)+" s"),r.nextLoadLevel=E,this.bwEstimator.sample(d,u.loaded),this.clearTimer(),t.loader&&(this.fragCurrent=this.partCurrent=null,t.loader.abort()),r.trigger(a.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:u})}}}}}},l.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if(r.type===k.b.MAIN&&Object(n.a)(r.sn)){var s=i?i.stats:r.stats,o=i?i.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+s.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:h},l.realBitrate=Math.round(8*u/h)}if(r.bitrateTest){var d={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(a.a.FRAG_BUFFERED,d),r.bitrateTest=!1}}},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part,n=i?i.stats:r.stats;if(!n.aborted&&r.type===k.b.MAIN&&"initSegment"!==r.sn){var a=n.parsing.end-n.loading.start;this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}},l.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},l.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},l.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=r.media,l=e?e.duration:t?t.duration:0,u=s?s.currentTime:0,h=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,c=(lt.bufferInfo(s,u,n.maxBufferHole).end-u)/h,f=this.findBestLevel(d,a,i,c,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(f>=0)return f;o.b.trace((c?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var g=l?Math.min(l,n.maxStarvationDelay):n.maxStarvationDelay,v=n.abrBandWidthFactor,p=n.abrBandWidthUpFactor;if(!c){var m=this.bitrateTestDelay;if(m)g=(l?Math.min(l,n.maxLoadingDelay):n.maxLoadingDelay)-m,o.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),v=p=1}return f=this.findBestLevel(d,a,i,c+g,v,p),Math.max(f,0)},l.findBestLevel=function(t,e,r,i,n,a){for(var s,l=this.fragCurrent,u=this.partCurrent,h=this.lastLoadedFragLevel,d=this.hls.levels,c=d[h],f=!(null==c||null===(s=c.details)||void 0===s||!s.live),g=null==c?void 0:c.codecSet,v=u?u.duration:l?l.duration:0,p=r;p>=e;p--){var m=d[p];if(m&&(!g||m.codecSet===g)){var y=m.details,T=(u?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||v,b=void 0;b=p<=h?n*t:a*t;var E=d[p].maxBitrate,S=E*T/b;if(o.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+p+"/"+Math.round(b)+"/"+E+"/"+T+"/"+i+"/"+S),b>E&&(!S||f&&!this.bitrateTestDelay||S0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),this.state=xt):(this.loadedmetadata=!1,this.state=Nt),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},l.doTick=function(){switch(this.state){case xt:this.doTickIdle();break;case Nt:var e,r=this.levels,i=this.trackId,n=null==r||null===(e=r[i])||void 0===e?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=Ht}break;case Ft:var a,s=performance.now(),l=this.retryDate;(!l||s>=l||null!==(a=this.media)&&void 0!==a&&a.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.state=xt);break;case Ht:var u=this.waitingData;if(u){var h=u.frag,d=u.part,c=u.cache,f=u.complete;if(void 0!==this.initPTS[h.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Mt;var g={frag:h,part:d,payload:c.flush(),networkDetails:null};this._handleFragmentLoadProgress(g),f&&t.prototype._handleFragmentLoadComplete.call(this,g)}else if(this.videoTrackCC!==this.waitingVideoCC)o.b.log("Waiting fragment cc ("+h.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var v=this.getLoadPosition(),p=lt.bufferInfo(this.mediaBuffer,v,this.config.maxBufferHole);mt(p.end,this.config.maxFragLookUpTolerance,h)<0&&(o.b.log("Waiting fragment cc ("+h.cc+") @ "+h.start+" cancelled because another fragment at "+p.end+" is needed"),this.clearWaitingFragment())}}else this.state=xt}this.onTickEnd()},l.clearWaitingFragment=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=xt)},l.onTickEnd=function(){var t=this.media;if(t&&t.readyState){var e=(this.mediaBuffer?this.mediaBuffer:t).buffered;!this.loadedmetadata&&e.length&&(this.loadedmetadata=!0),this.lastCurrentTime=t.currentTime}},l.doTickIdle=function(){var t,e,r=this.hls,i=this.levels,n=this.media,s=this.trackId,o=r.config;if(i&&i[s]&&(n||!this.startFragRequested&&o.startFragPrefetch)){var l=i[s].details;if(!l||l.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(l))this.state=Nt;else{this.bufferFlushed&&(this.bufferFlushed=!1,this.afterBufferFlushed(this.mediaBuffer?this.mediaBuffer:this.media,u.a.AUDIO,k.b.AUDIO));var h=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,k.b.AUDIO);if(null!==h){var d=h.len,c=this.getMaxBufferLength(),f=this.audioSwitch;if(!(d>=c)||f){if(!f&&this._streamEnded(h,l))return r.trigger(a.a.BUFFER_EOS,{type:"audio"}),void(this.state=Kt);var g=l.fragments[0].start,v=h.end;if(f){var p=this.getLoadPosition();v=p,l.PTSKnown&&pg||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=g+.05)}var m=this.getNextFragment(v,l);m?"identity"!==(null===(t=m.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=m.decryptdata)&&void 0!==e&&e.key?this.loadFragment(m,l,v):this.loadKey(m,l):this.bufferFlushed=!0}}}}},l.getMaxBufferLength=function(){var e=t.prototype.getMaxBufferLength.call(this),r=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,k.b.MAIN);return null===r?e:Math.max(e,r.len)},l.onMediaDetaching=function(){this.videoBuffer=null,t.prototype.onMediaDetaching.call(this)},l.onAudioTracksUpdated=function(t,e){var r=e.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(t){return new j(t)}))},l.onAudioTrackSwitching=function(t,e){var r=!!e.url;this.trackId=e.id;var i=this.fragCurrent;null!=i&&i.loader&&i.loader.abort(),this.fragCurrent=null,this.clearWaitingFragment(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.audioSwitch=!0,this.state=xt):this.state=Ot,this.tick()},l.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1},l.onLevelLoaded=function(t,e){this.mainDetails=e.details},l.onAudioTrackLoaded=function(t,e){var r,i=this.levels,n=e.details,a=e.id;if(i){this.log("Track "+a+" loaded ["+n.startSN+","+n.endSN+"],duration:"+n.totalduration);var s=i[a],o=0;if(n.live||null!==(r=s.details)&&void 0!==r&&r.live){var l=this.mainDetails;if(n.fragments[0]||(n.deltaUpdateFailed=!0),n.deltaUpdateFailed||!l)return;!s.details&&n.hasProgramDateTime&&l.hasProgramDateTime?(gt(n,l),o=n.fragments[0].start):o=this.alignPlaylists(n,s.details)}s.details=n,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(s.details,o),this.state!==Nt||this.waitForCdnTuneIn(n)||(this.state=xt),this.tick()}else this.warn("Audio tracks were reset while loading level "+a)},l._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,n=t.payload,a=this.config,s=this.trackId,l=this.levels;if(l){var u=l[s],h=u.details,d=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2",c=this.transmuxer;c||(c=this.transmuxer=new Jt(this.hls,k.b.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var f=this.initPTS[r.cc],g=null===(e=r.initSegment)||void 0===e?void 0:e.data;if(void 0!==f){var v=i?i.index:-1,p=-1!==v,m=new ut(r.level,r.sn,r.stats.chunkCount,n.byteLength,v,p);c.push(n,g,d,"",r,i,h.totalduration,!1,m,f)}else{o.b.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+s),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new oe.a,complete:!1}).cache.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=Ht}}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},l._handleFragmentLoadComplete=function(e){this.waitingData?this.waitingData.complete=!0:t.prototype._handleFragmentLoadComplete.call(this,e)},l.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},l.onBufferCreated=function(t,e){var r=e.tracks.audio;r&&(this.mediaBuffer=r.buffer),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer)},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part;r.type===k.b.AUDIO&&(this.fragContextChanged(r)?this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+this.audioSwitch):("initSegment"!==r.sn&&(this.fragPrevious=r,this.audioSwitch&&(this.audioSwitch=!1,this.hls.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:this.trackId}))),this.fragBufferedComplete(r,i)))},l.onError=function(e,r){switch(r.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(k.b.AUDIO,r);break;case s.a.AUDIO_TRACK_LOAD_ERROR:case s.a.AUDIO_TRACK_LOAD_TIMEOUT:this.state!==jt&&this.state!==Ot&&(this.state=r.fatal?jt:xt,this.warn(r.details+" while loading frag, switching to "+this.state+" state"));break;case s.a.BUFFER_FULL_ERROR:if("audio"===r.parent&&(this.state===Ut||this.state===Bt)){var i=!0,n=this.getFwdBufferInfo(this.mediaBuffer,k.b.AUDIO);n&&n.len>.5&&(i=!this.reduceMaxBufferLength(n.len)),i&&(this.warn("Buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.resetLoadingState()}}},l.onBufferFlushed=function(t,e){e.type===u.a.AUDIO&&(this.bufferFlushed=!0)},l._handleTransmuxComplete=function(t){var e,r="audio",i=this.hls,n=t.remuxResult,s=t.chunkMeta,o=this.getCurrentContext(s);if(!o)return this.warn("The loading context changed while buffering fragment "+s.sn+" of level "+s.level+". This chunk will not be buffered."),void this.resetLiveStartWhenNotLoaded(s.level);var l=o.frag,h=o.part,d=n.audio,c=n.text,f=n.id3,g=n.initSegment;if(!this.fragContextChanged(l)){if(this.state=Ut,this.audioSwitch&&d&&this.completeAudioSwitch(),null!=g&&g.tracks&&(this._bufferInitSegment(g.tracks,l,s),i.trigger(a.a.FRAG_PARSING_INIT_SEGMENT,{frag:l,id:r,tracks:g.tracks})),d){var v=d.startPTS,p=d.endPTS,m=d.startDTS,y=d.endDTS;h&&(h.elementaryStreams[u.a.AUDIO]={startPTS:v,endPTS:p,startDTS:m,endDTS:y}),l.setElementaryStreamInfo(u.a.AUDIO,v,p,m,y),this.bufferFragmentData(d,l,h,s)}if(null!=f&&null!==(e=f.samples)&&void 0!==e&&e.length){var T=le({frag:l,id:r},f);i.trigger(a.a.FRAG_PARSING_METADATA,T)}if(c){var b=le({frag:l,id:r},c);i.trigger(a.a.FRAG_PARSING_USERDATA,b)}}},l._bufferInitSegment=function(t,e,r){if(this.state===Ut){t.video&&delete t.video;var i=t.audio;if(i){i.levelCodec=i.codec,i.id="audio",this.log("Init audio buffer, container:"+i.container+", codecs[parsed]=["+i.codec+"]"),this.hls.trigger(a.a.BUFFER_CODECS,t);var n=i.initSegment;if(null!=n&&n.byteLength){var s={type:"audio",frag:e,part:null,chunkMeta:r,parent:e.type,data:n};this.hls.trigger(a.a.BUFFER_APPENDING,s)}this.tick()}}},l.loadFragment=function(e,r,i){var a=this.fragmentTracker.getState(e);this.fragCurrent=e,(this.audioSwitch||a===tt.NOT_LOADED||a===tt.PARTIAL)&&("initSegment"===e.sn?this._loadInitSegment(e):r.live&&!Object(n.a)(this.initPTS[e.cc])?(this.log("Waiting for video PTS in continuity counter "+e.cc+" of live stream before loading audio fragment "+e.sn+" of level "+this.trackId),this.state=Ht):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)))},l.completeAudioSwitch=function(){var e=this.hls,r=this.media,i=this.trackId;r&&(this.log("Switching audio track : flushing all audio"),t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.audioSwitch=!1,e.trigger(a.a.AUDIO_TRACK_SWITCHED,{id:i})},i}(Wt);function de(t,e){for(var r=0;r=e.length)this.warn("Invalid id passed to audio-track controller");else{this.clearTimer();var r=e[this.trackId];this.log("Now switching to audio-track index "+t);var i=e[t],n=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,h=i.url;if(this.trackId=t,this.trackName=l,this.selectDefaultTrack=!1,this.hls.trigger(a.a.AUDIO_TRACK_SWITCHING,{id:n,groupId:o,name:l,type:u,url:h}),!i.details||i.details.live){var d=this.switchParams(i.url,null==r?void 0:r.details);this.loadPlaylist(d)}}},u.selectInitialTrack=function(){this.tracksInGroup;var t=this.trackName,e=this.findTrackId(t)||this.findTrackId();-1!==e?this.setAudioTrack(e):(this.warn("No track found for running audio group-ID: "+this.groupId),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))},u.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r)}}},l.onBufferFlushing=function(t,e){var r=e.startOffset,i=e.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=this.currentTrackId,a=this.levels;if(!a.length||!a[n]||!a[n].details)return;var s=i-a[n].details.targetduration;if(s<=0)return;e.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(t){for(var e=0;e=s.length||n!==a)&&o){if(this.mediaBuffer=this.mediaBufferTimeRanges,i.live||null!==(r=o.details)&&void 0!==r&&r.live){var l=this.mainDetails;if(i.deltaUpdateFailed||!l)return;var u=l.fragments[0];if(o.details)0===this.alignPlaylists(i,o.details)&&u&&z(i,u.start);else i.hasProgramDateTime&&l.hasProgramDateTime?gt(i,l):u&&z(i,u.start)}if(o.details=i,this.levelLastLoaded=n,this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===xt)pt(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}},l._handleFragmentLoadComplete=function(t){var e=t.frag,r=t.payload,i=e.decryptdata,n=this.hls;if(!this.fragContextChanged(e)&&r&&r.byteLength>0&&i&&i.key&&i.iv&&"AES-128"===i.method){var s=performance.now();this.decrypter.webCryptoDecrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).then((function(t){var r=performance.now();n.trigger(a.a.FRAG_DECRYPTED,{frag:e,payload:t,stats:{tstart:s,tdecrypt:r}})}))}},l.doTick=function(){if(this.media){if(this.state===xt){var t,e=this.currentTrackId,r=this.levels;if(!r.length||!r[e]||!r[e].details)return;var i=r[e].details,n=i.targetduration,a=this.config,s=this.media,o=lt.bufferedInfo(this.mediaBufferTimeRanges,s.currentTime-n,a.maxBufferHole),l=o.end;if(o.len>this.getMaxBufferLength()+n)return;var u,h=i.fragments,d=h.length,c=i.edge,f=this.fragPrevious;if(l-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},l.pollTrackChange=function(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)},l.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Te(this.media.textTracks).forEach((function(t){x(t)})),this.subtitleTrack=-1,this.media=null)},l.onManifestLoading=function(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0},l.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},l.onSubtitleTrackLoaded=function(t,e){var r=e.id,i=e.details,n=this.trackId,a=this.tracksInGroup[n];if(a){var s=a.details;a.details=e.details,this.log("subtitle track "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,e,s))}else this.warn("Invalid subtitle track id "+r)},l.onLevelLoading=function(t,e){this.switchLevel(e.level)},l.onLevelSwitching=function(t,e){this.switchLevel(e.level)},l.switchLevel=function(t){var e=this.hls.levels[t];if(null!=e&&e.textGroupIds){var r=e.textGroupIds[e.urlId];if(this.groupId!==r){var i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0,n=this.tracks.filter((function(t){return!r||t.groupId===r}));this.tracksInGroup=n;var s=this.findTrackId(null==i?void 0:i.name)||this.findTrackId();this.groupId=r;var o={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(a.a.SUBTITLE_TRACKS_UPDATED,o),-1!==s&&this.setSubtitleTrack(s,i)}}},l.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=i.length)){this.clearTimer();var n=i[t];if(this.log("Switching to subtitle track "+t),this.trackId=t,n){var s=n.id,o=n.groupId,l=void 0===o?"":o,u=n.name,h=n.type,d=n.url;this.hls.trigger(a.a.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:h,url:d});var c=this.switchParams(n.url,null==e?void 0:e.details);this.loadPlaylist(c)}else this.hls.trigger(a.a.SUBTITLE_TRACK_SWITCH,{id:t})}}else this.queuedDefaultTrack=t},l.onTextTracksChanged=function(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),this.media&&this.hls.config.renderTextTracksNatively){for(var t=-1,e=Te(this.media.textTracks),r=0;r0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null},e.registerListeners=function(){var t=this.hls;t.on(a.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.a.BUFFER_RESET,this.onBufferReset,this),t.on(a.a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(a.a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.a.BUFFER_EOS,this.onBufferEos,this),t.on(a.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.a.FRAG_PARSED,this.onFragParsed,this),t.on(a.a.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(a.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.a.BUFFER_RESET,this.onBufferReset,this),t.off(a.a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(a.a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.a.BUFFER_EOS,this.onBufferEos,this),t.off(a.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.a.FRAG_PARSED,this.onFragParsed,this),t.off(a.a.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new Se(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,o.b.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&Le){var i=this.mediaSource=new Le;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(o.b.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){o.b.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):o.b.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(a.a.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){var r=t.sourceBuffer[e];try{r&&(t.removeBufferListeners(e),t.mediaSource&&t.mediaSource.removeSourceBuffer(r),t.sourceBuffer[e]=void 0)}catch(t){o.b.warn("[buffer-controller]: Failed to reset the "+e+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length;Object.keys(e).forEach((function(t){if(i){var n=r.tracks[t];if(n&&"function"==typeof n.buffer.changeType){var a=e[t],s=a.codec,o=a.levelCodec,l=a.container;if((n.levelCodec||n.codec).replace(Ae,"$1")!==(o||s).replace(Ae,"$1")){var u=l+";codecs="+(o||s);r.appendChangeType(t,u)}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,n={execute:function(){var n=r.sourceBuffer[t];n&&(o.b.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),n.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){o.b.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(n,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,n=this.operationQueue,l=this.tracks,u=e.data,h=e.type,d=e.frag,c=e.part,f=e.chunkMeta,g=f.buffering[h],v=self.performance.now();g.start=v;var p=d.stats.buffering,m=c?c.stats.buffering:null;0===p.start&&(p.start=v),m&&0===m.start&&(m.start=v);var y=l.audio,T="audio"===h&&1===f.id&&"audio/mpeg"===(null==y?void 0:y.container),b={execute:function(){if(g.executeStart=self.performance.now(),T){var t=r.sourceBuffer[h];if(t){var e=d.start-t.timestampOffset;Math.abs(e)>=.1&&(o.b.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+d.start+" (delta: "+e+") sn: "+d.sn+")"),t.timestampOffset=d.start)}}r.appendExecutor(u,h)},onStart:function(){},onComplete:function(){var t=self.performance.now();g.executeEnd=g.end=t,0===p.first&&(p.first=t),m&&0===m.first&&(m.first=t);var e=r.sourceBuffer,i={};for(var n in e)i[n]=lt.getBuffered(e[n]);r.appendError=0,r.hls.trigger(a.a.BUFFER_APPENDED,{type:h,frag:d,part:c,chunkMeta:f,parent:d.type,timeRanges:i})},onError:function(t){o.b.error("[buffer-controller]: Error encountered while trying to append to the "+h+" SourceBuffer",t);var e={type:s.b.MEDIA_ERROR,parent:d.type,details:s.a.BUFFER_APPEND_ERROR,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=s.a.BUFFER_FULL_ERROR:(r.appendError++,e.details=s.a.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(o.b.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0)),i.trigger(a.a.ERROR,e)}};n.append(b,h)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,n=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(a.a.BUFFER_FLUSHED,{type:t})},onError:function(e){o.b.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(n(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(n(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,n=e.part,s=[],l=n?n.elementaryStreams:i.elementaryStreams;l[u.a.AUDIOVIDEO]?s.push("audiovideo"):(l[u.a.AUDIO]&&s.push("audio"),l[u.a.VIDEO]&&s.push("video"));0===s.length&&o.b.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,n&&(n.stats.buffering.end=t);var e=n?n.stats:i.stats;r.hls.trigger(a.a.FRAG_BUFFERED,{frag:i,part:n,stats:e,id:i.type})}),s)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var n=r.sourceBuffer[i];return e.type&&e.type!==i||n&&!n.ended&&(n.ended=!0,o.b.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),t&&!(n&&!n.ended)}),!0)&&this.blockBuffers((function(){var t=r.mediaSource;t&&"open"===t.readyState&&t.endOfStream()}))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==e){var s=this.getSourceBufferTypes();if(s.length){var o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(Object(n.a)(o)&&!(o<0)){var l=r.currentTime,u=e.levelTargetDuration,h=Math.max(o,u),d=Math.floor(l/u)*u-h;s.forEach((function(r){var n=i[r];if(n){var s=lt.getBuffered(n);s.length>0&&d>s.start(0)&&(t.trigger(a.a.BACK_BUFFER_REACHED,{bufferEnd:d}),e.live&&t.trigger(a.a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d}),t.trigger(a.a.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:r}))}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,a=t.fragments[0].start+t.totalduration,s=r.duration,l=Object(n.a)(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(o.b.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(a>l&&a>s||!Object(n.a)(s))&&(o.b.log("[buffer-controller]: Updating Media Source duration to "+a.toFixed(3)),i.duration=a)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),n=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,n)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var n=this.getSourceBufferTypes();if(0===n.length)return void this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});n.forEach((function(t){e.executeNext(t)}))}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var n in t)if(!e[n]){var l=t[n];if(!l)throw Error("source buffer exists for track "+n+", however track does not");var u=l.levelCodec||l.codec,h=l.container+";codecs="+u;o.b.log("[buffer-controller]: creating sourceBuffer("+h+")");try{var d=e[n]=r.addSourceBuffer(h),c=n;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[n]={buffer:d,codec:u,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(t){o.b.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:h})}}i&&this.hls.trigger(a.a.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){o.b.error("[buffer-controller]: "+t+" SourceBuffer error",e),this.hls.trigger(a.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(t);r&&r.onError(e)},e.removeExecutor=function(t,e,r){var i=this.media,a=this.mediaSource,s=this.operationQueue,l=this.sourceBuffer[t];if(!i||!a||!l)return o.b.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(t);var u=Object(n.a)(i.duration)?i.duration:1/0,h=Object(n.a)(a.duration)?a.duration:1/0,d=Math.max(0,e),c=Math.min(r,u,h);c>d?(o.b.log("[buffer-controller]: Removing ["+d+","+c+"] from the "+t+" SourceBuffer"),l.remove(d,c)):s.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return o.b.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return o.b.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(t);var i=this.operationQueue,n=e.map((function(t){return i.appendBlocker(t)}));Promise.all(n).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var n=r.bind(this,t);this.listeners[t].push({event:e,listener:n}),i.addEventListener(e,n)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}(),De={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},ke=function(t){var e=t;return De.hasOwnProperty(t)&&(e=De[t]),String.fromCharCode(e)},_e={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ie={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ce={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},we={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Oe=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];!function(t){t[t.ERROR=0]="ERROR",t[t.TEXT=1]="TEXT",t[t.WARNING=2]="WARNING",t[t.INFO=2]="INFO",t[t.DEBUG=3]="DEBUG",t[t.DATA=3]="DATA"}(be||(be={}));var xe=function(){function t(){this.time=null,this.verboseLevel=be.ERROR}return t.prototype.log=function(t,e){this.verboseLevel>=t&&o.b.log(this.time+" ["+t+"] "+e)},t}(),Pe=function(t){for(var e=[],r=0;r100&&(this.logger.log(be.DEBUG,"Too large cursor position "+this.pos),this.pos=100)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var r=this.pos+1;r=144&&this.backSpace();var e=ke(t);this.pos>=100?this.logger.log(be.ERROR,"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e<100;e++)this.chars[e].reset()},e.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.getTextString=function(){for(var t=[],e=!0,r=0;r<100;r++){var i=this.chars[r].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")},e.setPenStyles=function(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)},t}(),Ue=function(){function t(t){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(var e=0;e<15;e++)this.rows.push(new Ne(t));this.logger=t,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}var e=t.prototype;return e.reset=function(){for(var t=0;t<15;t++)this.rows[t].clear();this.currRow=14},e.equals=function(t){for(var e=!0,r=0;r<15;r++)if(!this.rows[r].equals(t.rows[r])){e=!1;break}return e},e.copy=function(t){for(var e=0;e<15;e++)this.rows[e].copy(t.rows[e])},e.isEmpty=function(){for(var t=!0,e=0;e<15;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t},e.backSpace=function(){this.rows[this.currRow].backSpace()},e.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.insertChar=function(t){this.rows[this.currRow].insertChar(t)},e.setPen=function(t){this.rows[this.currRow].setPenStyles(t)},e.moveCursor=function(t){this.rows[this.currRow].moveCursor(t)},e.setCursor=function(t){this.logger.log(be.INFO,"setCursor: "+t),this.rows[this.currRow].setCursor(t)},e.setPAC=function(t){this.logger.log(be.INFO,"pacData = "+JSON.stringify(t));var e=t.row-1;if(this.nrRollUpRows&&e0&&(r=t?"["+e.join(" | ")+"]":e.join("\n")),r},e.getTextAndFormat=function(){return this.rows},t}(),Be=function(){function t(t,e,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Ue(r),this.nonDisplayedMemory=new Ue(r),this.lastOutputScreen=new Ue(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var e=t.prototype;return e.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(be.INFO,"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)},e.insertChars=function(t){for(var e=0;e=46,e.italics)e.foreground="white";else{var r=Math.floor(t/2)-16;e.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(be.INFO,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}();function Ge(t,e,r){r.a=t,r.b=e}function Ke(t,e,r){return r.a===t&&r.b===e}var je=function(){function t(t,e,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new xe;this.channels=[null,new Be(t,e,i),new Be(t+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var r,i,n,a=!1;this.logger.time=t;for(var s=0;s ("+Pe([i,n])+")"),(r=this.parseCmd(i,n))||(r=this.parseMidrow(i,n)),r||(r=this.parsePAC(i,n)),r||(r=this.parseBackgroundAttributes(i,n)),!r&&(a=this.parseChars(i,n))){var o=this.currentChannel;if(o&&o>0)this.channels[o].insertChars(a);else this.logger.log(be.WARNING,"No channel found yet. TEXT-MODE?")}r||a||this.logger.log(be.WARNING,"Couldn't parse cleaned data "+Pe([i,n])+" orig: "+Pe([e[s],e[s+1]]))}},e.parseCmd=function(t,e){var r=this.cmdHistory;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;if(Ke(t,e,r))return Ge(null,null,r),this.logger.log(be.DEBUG,"Repeated command ("+Pe([t,e])+") is dropped"),!0;var i=20===t||21===t||23===t?1:2,n=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?n.ccRCL():33===e?n.ccBS():34===e?n.ccAOF():35===e?n.ccAON():36===e?n.ccDER():37===e?n.ccRU(2):38===e?n.ccRU(3):39===e?n.ccRU(4):40===e?n.ccFON():41===e?n.ccRDC():42===e?n.ccTR():43===e?n.ccRTD():44===e?n.ccEDM():45===e?n.ccCR():46===e?n.ccENM():47===e&&n.ccEOC():n.ccTO(e-32),Ge(t,e,r),this.currentChannel=i,!0},e.parseMidrow=function(t,e){var r=0;if((17===t||25===t)&&e>=32&&e<=47){if((r=17===t?1:2)!==this.currentChannel)return this.logger.log(be.ERROR,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(e),this.logger.log(be.DEBUG,"MIDROW ("+Pe([t,e])+")"),!0)}return!1},e.parsePAC=function(t,e){var r,i=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;if(Ke(t,e,i))return Ge(null,null,i),!0;var n=t<=23?1:2;r=e>=64&&e<=95?1===n?_e[t]:Ce[t]:1===n?Ie[t]:we[t];var a=this.channels[n];return!!a&&(a.setPAC(this.interpretPAC(r,e)),Ge(t,e,i),this.currentChannel=n,!0)},e.interpretPAC=function(t,e){var r,i={color:null,italics:!1,indent:null,underline:!1,row:t};return r=e>95?e-96:e-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},e.parseChars=function(t,e){var r,i,n=null,a=null;(t>=25?(r=2,a=t-8):(r=1,a=t),a>=17&&a<=19)?(i=17===a?e+80:18===a?e+112:e+144,this.logger.log(be.INFO,"Special char '"+ke(i)+"' in channel "+r),n=[i]):t>=32&&t<=127&&(n=0===e?[t]:[t,e]);if(n){var s=Pe(n);this.logger.log(be.DEBUG,"Char codes = "+s.join(",")),Ge(t,e,this.cmdHistory)}return n},e.parseBackgroundAttributes=function(t,e){var r;if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;var i={};16===t||24===t?(r=Math.floor((e-32)/2),i.background=Oe[r],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));var n=t<=23?1:2;return this.channels[n].setBkgData(i),Ge(t,e,this.cmdHistory),!0},e.reset=function(){for(var t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[],this.startTime=null},t}(),Ve=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function r(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var r=e.toLowerCase();return!!~t.indexOf(r)&&r}function i(t){return r(e,t)}function n(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return b},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),We=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function Ye(t){function e(t,e,r,i){return 3600*(0|t)+60*(0|e)+(0|r)+parseFloat(i||0)}var r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}var qe=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,r){return r?this.has(t)?this.values[t]:e[r]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,r){for(var i=0;i=0&&r<=100)return this.set(t,r),!0}return!1},t}();function Xe(t,e,r,i){var n=i?t.split(i):[t];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);if(2===s.length)e(s[0],s[1])}}var ze=new Ve(0,0,""),Qe="middle"===ze.align?"middle":"center";function $e(t,e,r){var i=t;function n(){var e=Ye(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),"--\x3e"!==t.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.substr(3),a(),e.endTime=n(),a(),function(t,e){var i=new qe;Xe(t,(function(t,e){var n;switch(t){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===e){i.set(t,r[a].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":n=e.split(","),i.integer(t,n[0]),i.percent(t,n[0])&&i.set("snapToLines",!1),i.alt(t,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",Qe,"end"]);break;case"position":n=e.split(","),i.percent(t,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",Qe,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Qe,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===ze.line&&(n=-1),e.line=n,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Qe);var a=i.get("position","auto");"auto"===a&&50===ze.position&&(a="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=a}(t,e)}function Je(t){return t.replace(//gi,"\n")}var Ze=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new We,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function r(){var t=e.buffer,r=0;for(t=Je(t);r>>0).toString()};function ar(t,e,r){return nr(t.toString())+nr(e.toString())+nr(r)}function sr(t,e,r,i,a,s,o,l){var u,h=new Ze,d=Object(M.f)(new Uint8Array(t)).trim().replace(rr,"\n").split("\n"),c=[],f=Object(tr.a)(e,r),g="00:00.000",v=0,p=0,m=!0,y=!1;h.oncue=function(t){var e=i[a],r=i.ccOffset,n=(v-f)/9e4;if(null!=e&&e.new&&(void 0!==p?r=i.ccOffset=e.start:function(t,e,r){var i=t[e],n=t[i.prevCC];if(!n||!n.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!==(a=n)&&void 0!==a&&a.new;){var a;t.ccOffset+=i.start-n.start,i.new=!1,n=t[(i=n).prevCC]}t.presentationOffset=r}(i,a,n)),n&&(r=n-i.presentationOffset),y){var o=t.endTime-t.startTime,l=Object(er.b)(9e4*(t.startTime+r-p),9e4*s)/9e4;t.startTime=l,t.endTime=l+o}var u=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(u)),t.id||(t.id=ar(t.startTime,t.endTime,u)),t.endTime>0&&c.push(t)},h.onparsingerror=function(t){u=t},h.onflush=function(){u?l(u):o(c)},d.forEach((function(t){if(m){if(ir(t,"X-TIMESTAMP-MAP=")){m=!1,y=!0,t.substr(16).split(",").forEach((function(t){ir(t,"LOCAL:")?g=t.substr(6):ir(t,"MPEGTS:")&&(v=parseInt(t.substr(7)))}));try{p=function(t){var e=parseInt(t.substr(-3)),r=parseInt(t.substr(-6,2)),i=parseInt(t.substr(-9,2)),a=t.length>9?parseInt(t.substr(0,t.indexOf(":"))):0;if(!(Object(n.a)(e)&&Object(n.a)(r)&&Object(n.a)(i)&&Object(n.a)(a)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*r,e+=6e4*i,e+=36e5*a}(g)/1e3}catch(t){y=!1,u=t}return}""===t&&(m=!1)}h.parse(t+"\n")})),h.flush()}function or(){return(or=Object.assign||function(t){for(var e=1;e=0&&(c[0]=Math.min(c[0],e),c[1]=Math.max(c[1],r),h=!0,f/(r-e)>.5))return}if(h||n.push([e,r]),this.config.renderTextTracksNatively){var g=this.captionsTracks[t];this.Cues.newCue(g,e,r,i)}else{var v=this.Cues.newCue(null,e,r,i);this.hls.trigger(a.a.CUES_PARSED,{type:"captions",cues:v,track:t})}},e.onInitPtsFound=function(t,e){var r=this,i=e.frag,n=e.id,s=e.initPTS,o=e.timescale,l=this.unparsedVttFrags;"main"===n&&(this.initPTS[i.cc]=s,this.timescale[i.cc]=o),l.length&&(this.unparsedVttFrags=[],l.forEach((function(t){r.onFragLoaded(a.a.FRAG_LOADED,t)})))},e.getExistingTrack=function(t){var e=this.media;if(e)for(var r=0;r0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},n.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(i,n){return t.isLevelAllowed(n,r.restrictedLevels)&&n<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},n.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},n.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},n.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},t.isLevelAllowed=function(t,e){return void 0===e&&(e=[]),-1===e.indexOf(t)},t.getMaxLevelByMediaSize=function(t,e,r){if(!t||!t.length)return-1;for(var i,n,a=t.length-1,s=0;s=e||o.height>=r)&&(i=o,!(n=t[s+1])||i.width!==n.width||i.height!==n.height)){a=s;break}}return a},e=t,i=[{key:"contentScaleFactor",get:function(){var t=1;try{t=self.devicePixelRatio}catch(t){}return t}}],(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*t.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*t.contentScaleFactor}}])&&Tr(e.prototype,r),i&&Tr(e,i),t}(),Sr=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(a.a.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(a.a.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var n=i-this.lastTime,s=r-this.lastDroppedFrames,l=e-this.lastDecodedFrames,u=1e3*s/n,h=this.hls;if(h.trigger(a.a.FPS_DROP,{currentDropped:s,currentDecoded:l,totalDroppedFrames:r}),u>0&&s>h.config.fpsDroppedMonitoringThreshold*l){var d=h.currentLevel;o.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=d)&&(d-=1,h.trigger(a.a.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:h.currentLevel}),h.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}();!function(t){t.WIDEVINE="com.widevine.alpha",t.PLAYREADY="com.microsoft.playready"}(br||(br={}));var Lr="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Ar(t,e){for(var r=0;r3)return void this.hls.trigger(a.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0});var u=3-this._requestLicenseFailureCount+1;o.b.warn("Retrying license request, "+u+" attempts left"),this._requestLicense(r,i)}}},n._generateLicenseRequestChallenge=function(t,e){switch(t.mediaKeySystemDomain){case br.WIDEVINE:return e}throw new Error("unsupported key-system: "+t.mediaKeySystemDomain)},n._requestLicense=function(t,e){o.b.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return o.b.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(a.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_NO_ACCESS,fatal:!0});try{var i=this.getLicenseServerUrl(r.mediaKeySystemDomain),n=this._createLicenseXhr(i,t,e);o.b.log("Sending license request to URL: "+i);var l=this._generateLicenseRequestChallenge(r,t);n.send(l)}catch(t){o.b.error("Failure requesting DRM license: "+t),this.hls.trigger(a.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}},n.onMediaAttached=function(t,e){if(this._emeEnabled){var r=e.media;this._media=r,r.addEventListener("encrypted",this._onMediaEncrypted)}},n.onMediaDetached=function(){var t=this._media,e=this._mediaKeysList;t&&(t.removeEventListener("encrypted",this._onMediaEncrypted),this._media=null,this._mediaKeysList=[],Promise.all(e.map((function(t){if(t.mediaKeysSession)return t.mediaKeysSession.close().catch((function(){}))}))).then((function(){return t.setMediaKeys(null)})).catch((function(){})))},n.onManifestParsed=function(t,e){if(this._emeEnabled){var r=e.levels.map((function(t){return t.audioCodec})).filter((function(t){return!!t})),i=e.levels.map((function(t){return t.videoCodec})).filter((function(t){return!!t}));this._attemptKeySystemAccess(br.WIDEVINE,r,i)}},e=t,(r=[{key:"requestMediaKeySystemAccess",get:function(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}])&&Ar(e.prototype,r),i&&Ar(e,i),t}();function Ir(t,e){for(var r=0;r=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Or(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,i=new Array(e);r-1?n+1:i.levels.length;e=i.levels.slice(0,a)}for(var s,o=wr(e);!(s=o()).done;){var l=s.value;l.bitrate>r&&(r=l.bitrate)}return r>0?r:NaN},e.getBufferLength=function(t){var e=this.hls.media,r=t===Rr.AUDIO?this.audioBuffer:this.videoBuffer;return r&&e?1e3*lt.bufferInfo(r,e.currentTime,this.config.maxBufferHole).len:NaN},e.createPlaylistLoader=function(){var t=this.config.pLoader,e=this.applyPlaylistData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},Cr(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},e.createFragmentLoader=function(){var t=this.config.fLoader,e=this.applyFragmentData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},Cr(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},t.uuid=function(){var t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.substr(e.lastIndexOf("/")+1)},t.serialize=function(t){for(var e,r=[],i=function(t){return!Number.isNaN(t)&&null!=t&&""!==t&&!1!==t},n=function(t){return Math.round(t)},a=function(t){return 100*n(t/100)},s={br:n,d:n,bl:a,dl:a,mtp:a,nor:function(t){return encodeURIComponent(t)},rtp:a,tb:n},o=wr(Object.keys(t||{}).sort());!(e=o()).done;){var l=e.value,u=t[l];if(i(u)&&!("v"===l&&1===u||"pr"==l&&1===u)){var h=s[l];h&&(u=h(u));var d=typeof u,c=void 0;c="ot"===l||"sf"===l||"st"===l?l+"="+u:"boolean"===d?l:"number"===d?l+"="+u:l+"="+JSON.stringify(u),r.push(c)}}return r.join(",")},t.toHeaders=function(e){for(var r={},i=["Object","Request","Session","Status"],n=[{},{},{},{}],a={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3},s=0,o=Object.keys(e);s=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===i){e.onreadystatechange=null,e.onprogress=null;var a=e.status;if(a>=200&&a<300){var s,l;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),l="arraybuffer"===t.responseType?(s=e.response).byteLength:(s=e.responseText).length,r.loaded=r.total=l,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,s,e),!this.callbacks)return;var h={url:e.responseURL,data:s};this.callbacks.onSuccess(h,r,t,e)}else r.retry>=n.maxRetry||a>=400&&a<499?(o.b.error(a+" while loading "+t.url),this.callbacks.onError({code:a,text:e.statusText},t,e)):(o.b.warn(a+" while loading "+t.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,n.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout)}},e.loadtimeout=function(){o.b.warn("timeout while loading "+this.context.url);var t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&Fr.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},t}();function Ur(t){var e="function"==typeof Map?new Map:void 0;return(Ur=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return Br(t,arguments,jr(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Kr(i,t)})(t)}function Br(t,e,r){return(Br=Gr()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var n=new(Function.bind.apply(t,i));return r&&Kr(n,r.prototype),n}).apply(null,arguments)}function Gr(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function Kr(t,e){return(Kr=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function jr(t){return(jr=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Hr(){return(Hr=Object.assign||function(t){for(var e=1;e=i&&n(e,r,a.flush(),t)):n(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function Wr(t,e){return new self.Request(t.url,e)}var Yr=function(t){var e,r;function i(e,r,i){var n;return(n=t.call(this,e)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,Kr(e,r),i}(Ur(Error)),qr=Vr,Xr=/\s/;function zr(){return(zr=Object.assign||function(t){for(var e=1;e=16?o--:o++;var f=Je(l.trim()),g=ar(e,r,f);t&&t.cues&&t.cues.getCueById(g)||((a=new h(e,r,f)).id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return t&&u.length&&(u.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),u.forEach((function(e){return O(t,e)}))),u}},enableCEA708Captions:!0,enableWebVTT:!0,enableIMSC1:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:pe,subtitleTrackController:Ee,timelineController:mr,audioStreamController:he,audioTrackController:fe,emeController:_r,cmcdController:Pr});function ti(t){var e=t.loader;e!==qr&&e!==Nr?(o.b.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=qr,t.progressive=!0,t.enableSoftwareAES=!0,o.b.log("[config]: Progressive streaming enabled, using FetchLoader"))}function ei(t,e){for(var r=0;re)return i;return 0}},{key:"maxAutoLevel",get:function(){var t=this.levels,e=this.autoLevelCapping;return-1===e&&t&&t.length?t.length-1:e}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&ei(e.prototype,r),n&&ei(e,n),t}();ri.defaultConfig=void 0}]).default})); -//# sourceMappingURL=hls.min.js.map \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/jquery.min.js b/node_modules/paellaplayer/build/player/javascript/jquery.min.js deleted file mode 100644 index b0614034a..000000000 --- a/node_modules/paellaplayer/build/player/javascript/jquery.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.5.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function D(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,j=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
            "],col:[2,"","
            "],tr:[2,"","
            "],td:[3,"","
            "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function qe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function Le(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="
            ",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=$e(y.pixelPosition,function(e,t){if(t)return t=Be(e,n),Me.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 00){var u=T.utils.clone(t)||{};u.position=[o,a],u.index=n.length,n.push(new T.Token(r.slice(o,s),u))}o=s+1}}return n},T.tokenizer.separator=/[\s\-]+/ -/*! - * lunr.Pipeline - * Copyright (C) 2020 Oliver Nightingale - */,T.Pipeline=function(){this._stack=[]},T.Pipeline.registeredFunctions=Object.create(null),T.Pipeline.registerFunction=function(e,t){t in this.registeredFunctions&&T.utils.warn("Overwriting existing registered function: "+t),e.label=t,T.Pipeline.registeredFunctions[e.label]=e},T.Pipeline.warnIfFunctionNotRegistered=function(e){e.label&&e.label in this.registeredFunctions||T.utils.warn("Function is not registered with pipeline. This may cause problems when serialising the index.\n",e)},T.Pipeline.load=function(e){var t=new T.Pipeline;return e.forEach((function(e){var r=T.Pipeline.registeredFunctions[e];if(!r)throw new Error("Cannot load unregistered function: "+e);t.add(r)})),t},T.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach((function(e){T.Pipeline.warnIfFunctionNotRegistered(e),this._stack.push(e)}),this)},T.Pipeline.prototype.after=function(e,t){T.Pipeline.warnIfFunctionNotRegistered(t);var r=this._stack.indexOf(e);if(-1==r)throw new Error("Cannot find existingFn");r+=1,this._stack.splice(r,0,t)},T.Pipeline.prototype.before=function(e,t){T.Pipeline.warnIfFunctionNotRegistered(t);var r=this._stack.indexOf(e);if(-1==r)throw new Error("Cannot find existingFn");this._stack.splice(r,0,t)},T.Pipeline.prototype.remove=function(e){var t=this._stack.indexOf(e);-1!=t&&this._stack.splice(t,1)},T.Pipeline.prototype.run=function(e){for(var t=this._stack.length,r=0;r1&&(se&&(r=n),s!=e);)i=r-t,n=t+Math.floor(i/2),s=this.elements[2*n];return s==e?2*n:s>e?2*n:sa?l+=2:o==a&&(t+=r[u+1]*i[l+1],u+=2,l+=2);return t},T.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},T.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),t=1,r=0;t0){var s,o=n.str.charAt(0);o in n.node.edges?s=n.node.edges[o]:(s=new T.TokenSet,n.node.edges[o]=s),1==n.str.length&&(s.final=!0),i.push({node:s,editsRemaining:n.editsRemaining,str:n.str.slice(1)})}if(0!=n.editsRemaining){if("*"in n.node.edges)var a=n.node.edges["*"];else{a=new T.TokenSet;n.node.edges["*"]=a}if(0==n.str.length&&(a.final=!0),i.push({node:a,editsRemaining:n.editsRemaining-1,str:n.str}),n.str.length>1&&i.push({node:n.node,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)}),1==n.str.length&&(n.node.final=!0),n.str.length>=1){if("*"in n.node.edges)var u=n.node.edges["*"];else{u=new T.TokenSet;n.node.edges["*"]=u}1==n.str.length&&(u.final=!0),i.push({node:u,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)})}if(n.str.length>1){var l,c=n.str.charAt(0),h=n.str.charAt(1);h in n.node.edges?l=n.node.edges[h]:(l=new T.TokenSet,n.node.edges[h]=l),1==n.str.length&&(l.final=!0),i.push({node:l,editsRemaining:n.editsRemaining-1,str:c+n.str.slice(2)})}}}return r},T.TokenSet.fromString=function(e){for(var t=new T.TokenSet,r=t,i=0,n=e.length;i=e;t--){var r=this.uncheckedNodes[t],i=r.child.toString();i in this.minimizedNodes?r.parent.edges[r.char]=this.minimizedNodes[i]:(r.child._str=i,this.minimizedNodes[i]=r.child),this.uncheckedNodes.pop()}} -/*! - * lunr.Index - * Copyright (C) 2020 Oliver Nightingale - */,T.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},T.Index.prototype.search=function(e){return this.query((function(t){new T.QueryParser(e,t).parse()}))},T.Index.prototype.query=function(e){for(var t=new T.Query(this.fields),r=Object.create(null),i=Object.create(null),n=Object.create(null),s=Object.create(null),o=Object.create(null),a=0;a1?1:e},T.Builder.prototype.k1=function(e){this._k1=e},T.Builder.prototype.add=function(e,t){var r=e[this._ref],i=Object.keys(this._fields);this._documents[r]=t||{},this.documentCount+=1;for(var n=0;n=this.length)return T.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},T.QueryLexer.prototype.width=function(){return this.pos-this.start},T.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},T.QueryLexer.prototype.backup=function(){this.pos-=1},T.QueryLexer.prototype.acceptDigitRun=function(){var e,t;do{t=(e=this.next()).charCodeAt(0)}while(t>47&&t<58);e!=T.QueryLexer.EOS&&this.backup()},T.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(T.QueryLexer.TERM)),e.ignore(),e.more())return T.QueryLexer.lexText},T.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(T.QueryLexer.EDIT_DISTANCE),T.QueryLexer.lexText},T.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(T.QueryLexer.BOOST),T.QueryLexer.lexText},T.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(T.QueryLexer.TERM)},T.QueryLexer.termSeparator=T.tokenizer.separator,T.QueryLexer.lexText=function(e){for(;;){var t=e.next();if(t==T.QueryLexer.EOS)return T.QueryLexer.lexEOS;if(92!=t.charCodeAt(0)){if(":"==t)return T.QueryLexer.lexField;if("~"==t)return e.backup(),e.width()>0&&e.emit(T.QueryLexer.TERM),T.QueryLexer.lexEditDistance;if("^"==t)return e.backup(),e.width()>0&&e.emit(T.QueryLexer.TERM),T.QueryLexer.lexBoost;if("+"==t&&1===e.width())return e.emit(T.QueryLexer.PRESENCE),T.QueryLexer.lexText;if("-"==t&&1===e.width())return e.emit(T.QueryLexer.PRESENCE),T.QueryLexer.lexText;if(t.match(T.QueryLexer.termSeparator))return T.QueryLexer.lexTerm}else e.escapeCharacter()}},T.QueryParser=function(e,t){this.lexer=new T.QueryLexer(e),this.query=t,this.currentClause={},this.lexemeIdx=0},T.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=T.QueryParser.parseClause;e;)e=e(this);return this.query},T.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},T.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},T.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},T.QueryParser.parseClause=function(e){var t=e.peekLexeme();if(null!=t)switch(t.type){case T.QueryLexer.PRESENCE:return T.QueryParser.parsePresence;case T.QueryLexer.FIELD:return T.QueryParser.parseField;case T.QueryLexer.TERM:return T.QueryParser.parseTerm;default:var r="expected either a field or a term, found "+t.type;throw t.str.length>=1&&(r+=" with value '"+t.str+"'"),new T.QueryParseError(r,t.start,t.end)}},T.QueryParser.parsePresence=function(e){var t=e.consumeLexeme();if(null!=t){switch(t.str){case"-":e.currentClause.presence=T.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=T.Query.presence.REQUIRED;break;default:var r="unrecognised presence operator'"+t.str+"'";throw new T.QueryParseError(r,t.start,t.end)}var i=e.peekLexeme();if(null==i){r="expecting term or field, found nothing";throw new T.QueryParseError(r,t.start,t.end)}switch(i.type){case T.QueryLexer.FIELD:return T.QueryParser.parseField;case T.QueryLexer.TERM:return T.QueryParser.parseTerm;default:r="expecting term or field, found '"+i.type+"'";throw new T.QueryParseError(r,i.start,i.end)}}},T.QueryParser.parseField=function(e){var t=e.consumeLexeme();if(null!=t){if(-1==e.query.allFields.indexOf(t.str)){var r=e.query.allFields.map((function(e){return"'"+e+"'"})).join(", "),i="unrecognised field '"+t.str+"', possible fields: "+r;throw new T.QueryParseError(i,t.start,t.end)}e.currentClause.fields=[t.str];var n=e.peekLexeme();if(null==n){i="expecting term, found nothing";throw new T.QueryParseError(i,t.start,t.end)}switch(n.type){case T.QueryLexer.TERM:return T.QueryParser.parseTerm;default:i="expecting term, found '"+n.type+"'";throw new T.QueryParseError(i,n.start,n.end)}}},T.QueryParser.parseTerm=function(e){var t=e.consumeLexeme();if(null!=t){e.currentClause.term=t.str.toLowerCase(),-1!=t.str.indexOf("*")&&(e.currentClause.usePipeline=!1);var r=e.peekLexeme();if(null!=r)switch(r.type){case T.QueryLexer.TERM:return e.nextClause(),T.QueryParser.parseTerm;case T.QueryLexer.FIELD:return e.nextClause(),T.QueryParser.parseField;case T.QueryLexer.EDIT_DISTANCE:return T.QueryParser.parseEditDistance;case T.QueryLexer.BOOST:return T.QueryParser.parseBoost;case T.QueryLexer.PRESENCE:return e.nextClause(),T.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+r.type+"'";throw new T.QueryParseError(i,r.start,r.end)}else e.nextClause()}},T.QueryParser.parseEditDistance=function(e){var t=e.consumeLexeme();if(null!=t){var r=parseInt(t.str,10);if(isNaN(r)){var i="edit distance must be numeric";throw new T.QueryParseError(i,t.start,t.end)}e.currentClause.editDistance=r;var n=e.peekLexeme();if(null!=n)switch(n.type){case T.QueryLexer.TERM:return e.nextClause(),T.QueryParser.parseTerm;case T.QueryLexer.FIELD:return e.nextClause(),T.QueryParser.parseField;case T.QueryLexer.EDIT_DISTANCE:return T.QueryParser.parseEditDistance;case T.QueryLexer.BOOST:return T.QueryParser.parseBoost;case T.QueryLexer.PRESENCE:return e.nextClause(),T.QueryParser.parsePresence;default:i="Unexpected lexeme type '"+n.type+"'";throw new T.QueryParseError(i,n.start,n.end)}else e.nextClause()}},T.QueryParser.parseBoost=function(e){var t=e.consumeLexeme();if(null!=t){var r=parseInt(t.str,10);if(isNaN(r)){var i="boost must be numeric";throw new T.QueryParseError(i,t.start,t.end)}e.currentClause.boost=r;var n=e.peekLexeme();if(null!=n)switch(n.type){case T.QueryLexer.TERM:return e.nextClause(),T.QueryParser.parseTerm;case T.QueryLexer.FIELD:return e.nextClause(),T.QueryParser.parseField;case T.QueryLexer.EDIT_DISTANCE:return T.QueryParser.parseEditDistance;case T.QueryLexer.BOOST:return T.QueryParser.parseBoost;case T.QueryLexer.PRESENCE:return e.nextClause(),T.QueryParser.parsePresence;default:i="Unexpected lexeme type '"+n.type+"'";throw new T.QueryParseError(i,n.start,n.end)}else e.nextClause()}},b=this,P=function(){return T},"function"==typeof define&&define.amd?define(P):"object"==typeof exports?module.exports=P():b.lunr=P()}(); \ No newline at end of file diff --git a/node_modules/paellaplayer/build/player/javascript/paella_player.js b/node_modules/paellaplayer/build/player/javascript/paella_player.js deleted file mode 100644 index 2d5a09fad..000000000 --- a/node_modules/paellaplayer/build/player/javascript/paella_player.js +++ /dev/null @@ -1,24694 +0,0 @@ -"use strict"; - -var _this5 = void 0; - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } - -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } - -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community 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.osedu.org/licenses/ECL-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. -*/ -var GlobalParams = { - video: { - zIndex: 1 - }, - background: { - zIndex: 0 - } -}; -window.paella = window.paella || {}; -paella.player = null; -paella.version = "6.5.6 - build: 58bc697e"; - -(function buildBaseUrl() { - if (window.paella_debug_baseUrl) { - paella.baseUrl = window.paella_debug_baseUrl; - } else { - paella.baseUrl = location.href.replace(/[^/]*$/, ''); - } -})(); - -paella.events = { - play: "paella:play", - pause: "paella:pause", - next: "paella:next", - previous: "paella:previous", - seeking: "paella:seeking", - seeked: "paella:seeked", - timeupdate: "paella:timeupdate", - timeUpdate: "paella:timeupdate", - seekTo: "paella:setseek", - endVideo: "paella:endvideo", - // Triggered when a single video stream ends (once per video) - ended: "paella:ended", - // Triggered when the video ends - seekToTime: "paella:seektotime", - setTrim: "paella:settrim", - setPlaybackRate: "paella:setplaybackrate", - setVolume: 'paella:setVolume', - setComposition: 'paella:setComposition', - loadStarted: 'paella:loadStarted', - loadComplete: 'paella:loadComplete', - loadPlugins: 'paella:loadPlugins', - error: 'paella:error', - documentChanged: 'paella:documentChanged', - didSaveChanges: 'paella:didsavechanges', - controlBarWillHide: 'paella:controlbarwillhide', - controlBarDidHide: 'paella:controlbardidhide', - controlBarDidShow: 'paella:controlbardidshow', - hidePopUp: 'paella:hidePopUp', - showPopUp: 'paella:showPopUp', - enterFullscreen: 'paella:enterFullscreen', - exitFullscreen: 'paella:exitFullscreen', - resize: 'paella:resize', - // params: { width:paellaPlayerContainer width, height:paellaPlayerContainer height } - videoZoomChanged: 'paella:videoZoomChanged', - audioTagChanged: 'paella:audiotagchanged', - zoomAvailabilityChanged: 'paella:zoomavailabilitychanged', - qualityChanged: 'paella:qualityChanged', - singleVideoReady: 'paella:singleVideoReady', - singleVideoUnloaded: 'paella:singleVideoUnloaded', - videoReady: 'paella:videoReady', - videoUnloaded: 'paella:videoUnloaded', - controlBarLoaded: 'paella:controlBarLoaded', - captionAdded: 'paella:caption:add', - // Event triggered when new caption is available. - captionsEnabled: 'paella:caption:enabled', - // Event triguered when a caption es enabled. - captionsDisabled: 'paella:caption:disabled', - // Event triguered when a caption es disabled. - profileListChanged: 'paella:profilelistchanged', - setProfile: 'paella:setprofile', - seekAvailabilityChanged: 'paella:seekAvailabilityChanged', - trigger: function trigger(event, params) { - $(document).trigger(event, params); - }, - bind: function bind(event, callback) { - $(document).bind(event, function (event, params) { - callback(event, params); - }); - }, - setupExternalListener: function setupExternalListener() { - window.addEventListener("message", function (event) { - if (event.data && event.data.event) { - paella.events.trigger(event.data.event, event.data.params); - } - }, false); - } -}; -paella.events.setupExternalListener(); - -(function () { - paella.utils = paella.utils || {}; // This class requires jquery - - paella.utils.ajax = { - // onSuccess/onFail(data,type,returnCode,rawData) - send: function send(type, params, onSuccess, onFail) { - this.assertParams(params); - var ajaxObj = jQuery.ajax({ - url: params.url, - data: params.params, - type: type - }); - - if (typeof onSuccess == 'function') { - ajaxObj.done(function (data, textStatus, jqXHR) { - var contentType = jqXHR.getResponseHeader('content-type'); - onSuccess(data, contentType, jqXHR.status, jqXHR.responseText); - }); - } - - if (typeof onFail == 'function') { - ajaxObj.fail(function (jqXHR, textStatus, error) { - onFail(textStatus + ' : ' + error, 'text/plain', jqXHR.status, jqXHR.responseText); - }); - } - }, - assertParams: function assertParams(params) { - if (!params.url) throw new Error("paella.utils.ajax.send: url parameter not found"); - if (!params.params) params.params = {}; - } - }; - - paella.utils.ajax["get"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('get', params, onSuccess, onFail); - }; - - paella.utils.ajax["post"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('post', params, onSuccess, onFail); - }; - - paella.utils.ajax["put"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('put', params, onSuccess, onFail); - }; - - paella.utils.ajax["delete"] = function (params, onSuccess, onFail) { - paella.utils.ajax.send('delete', params, onSuccess, onFail); - }; // TODO: AsyncLoader is deprecated and should be replaced by promises - - - var AsyncLoaderCallback = /*#__PURE__*/function () { - function AsyncLoaderCallback(name) { - _classCallCheck(this, AsyncLoaderCallback); - - this.name = name; - this.prevCb = null; - this.nextCb = null; - this.loader = null; - } - - _createClass(AsyncLoaderCallback, [{ - key: "load", - value: function load(onSuccess, onError) { - onSuccess(); // If error: onError() - } - }]); - - return AsyncLoaderCallback; - }(); - - paella.utils.AsyncLoaderCallback = AsyncLoaderCallback; - - var AjaxCallback = /*#__PURE__*/function (_paella$utils$AsyncLo) { - _inherits(AjaxCallback, _paella$utils$AsyncLo); - - var _super = _createSuper(AjaxCallback); - - function AjaxCallback(params, type) { - var _this; - - _classCallCheck(this, AjaxCallback); - - _this = _super.call(this); - _this.params = null; - _this.type = 'get'; - _this.data = null; - _this.mimeType = null; - _this.statusCode = null; - _this.rawData = null; - _this.name = "ajaxCallback"; - if (type) _this.type = type; - if (typeof params == 'string') _this.params = { - url: params - };else if (_typeof(params) == 'object') _this.params = params;else _this.params = {}; - return _this; - } - - _createClass(AjaxCallback, [{ - key: "getParams", - value: function getParams() { - return this.params; - } - }, { - key: "willLoad", - value: function willLoad(callback) {} - }, { - key: "didLoadSuccess", - value: function didLoadSuccess(callback) { - return true; - } - }, { - key: "didLoadFail", - value: function didLoadFail(callback) { - return false; - } - }, { - key: "load", - value: function load(onSuccess, onError) { - var This = this; - if (typeof this.willLoad == 'function') this.willLoad(this); - paella.utils.ajax.send(this.type, this.getParams(), function (data, type, code, rawData) { - var status = true; - This.data = data; - This.mimeType = type; - This.statusCode = code; - This.rawData = rawData; - if (typeof This.didLoadSuccess == 'function') status = This.didLoadSuccess(This); - if (status) onSuccess();else onError(); - }, function (data, type, code, rawData) { - var status = false; - This.data = data; - This.mimeType = type; - This.statusCode = code; - This.rawData = rawData; - if (typeof This.didLoadFail == 'function') status = This.didLoadFail(This); - if (status) onSuccess();else onError(); - }); - } - }]); - - return AjaxCallback; - }(paella.utils.AsyncLoaderCallback); - - paella.utils.AjaxCallback = AjaxCallback; - - var JSONCallback = /*#__PURE__*/function (_paella$utils$AjaxCal) { - _inherits(JSONCallback, _paella$utils$AjaxCal); - - var _super2 = _createSuper(JSONCallback); - - function JSONCallback(params, type) { - _classCallCheck(this, JSONCallback); - - return _super2.call(this, params, type); - } - - _createClass(JSONCallback, [{ - key: "didLoadSuccess", - value: function didLoadSuccess(callback) { - if (_typeof(callback.data) == 'object') return true; - - try { - callback.data = JSON.parse(callback.data); - return true; - } catch (e) { - callback.data = { - error: "Unexpected data format", - data: callback.data - }; - return false; - } - } - }]); - - return JSONCallback; - }(paella.utils.AjaxCallback); - - paella.utils.JSONCallback = JSONCallback; - - var AsyncLoader = /*#__PURE__*/function () { - function AsyncLoader() { - _classCallCheck(this, AsyncLoader); - - this.firstCb = null; - this.lastCb = null; - this.callbackArray = null; - this.generatedId = 0; - this.continueOnError = false; - this.errorCallbacks = null; - this.currentCb = null; - this.callbackArray = {}; - this.errorCallbacks = []; - this.generatedId = 0; - } - - _createClass(AsyncLoader, [{ - key: "clearError", - value: function clearError() { - this.errorCallbacks = []; - } - }, { - key: "addCallback", - value: function addCallback(cb, name) { - if (!name) { - name = "callback_" + this.generatedId++; - } - - cb.__cbName__ = name; - this.callbackArray[name] = cb; - - if (!this.firstCb) { - this.firstCb = cb; - this.currentCb = cb; - } - - cb.prevCb = this.lastCb; - if (this.lastCb) this.lastCb.nextCb = cb; - this.lastCb = cb; - cb.loader = this; - return cb; - } - }, { - key: "getCallback", - value: function getCallback(name) { - return this.callbackArray[name]; - } - }, { - key: "load", - value: function load(onSuccess, onError) { - console.warn("paella.utils.AsyncLoader is deprecated. Consider to replace it with JavaScript promises."); - var This = this; - - if (this.currentCb) { - this.currentCb.load(function () { - This.onComplete(This.currentCb, This.currentCb.__cbName__, true); - This.currentCb = This.currentCb.nextCb; - This.load(onSuccess, onError); - }, function () { - This.onComplete(This.currentCb, This.currentCb.__cbName__, false); - - if (This.continueOnError) { - This.errorCallbacks.push(This.currentCb); - This.currentCb = This.currentCb.nextCb; - This.load(onSuccess, onError); - } else if (typeof onError == 'function') { - onError(); - } - }); - } else if (typeof onSuccess == 'function') { - onSuccess(); - } - } - }, { - key: "onComplete", - value: function onComplete(callback, cbName, status) {} - }]); - - return AsyncLoader; - }(); - - paella.utils.AsyncLoader = AsyncLoader; -})(); - -(function () { - var g_delegateCallbacks = {}; - var g_dataDelegates = []; - - var DataDelegate = /*#__PURE__*/function () { - function DataDelegate() { - _classCallCheck(this, DataDelegate); - } - - _createClass(DataDelegate, [{ - key: "read", - value: function read(context, params, onSuccess) { - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }, { - key: "write", - value: function write(context, params, value, onSuccess) { - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }, { - key: "remove", - value: function remove(context, params, onSuccess) { - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }]); - - return DataDelegate; - }(); - - paella.DataDelegate = DataDelegate; - paella.dataDelegates = {}; - - var Data = /*#__PURE__*/function () { - function Data(config) { - _classCallCheck(this, Data); - - this._enabled = config.data.enabled; // Delegate callbacks - - var executedCallbacks = []; - - var _loop = function _loop(context) { - var callback = g_delegateCallbacks[context]; - var DelegateClass = null; - var delegateName = null; - - if (!executedCallbacks.some(function (execCallbackData) { - if (execCallbackData.callback == callback) { - delegateName = execCallbackData.delegateName; - return true; - } - })) { - DelegateClass = g_delegateCallbacks[context](); - delegateName = DelegateClass.name; - paella.dataDelegates[delegateName] = DelegateClass; - executedCallbacks.push({ - callback: callback, - delegateName: delegateName - }); - } - - if (!config.data.dataDelegates[context]) { - config.data.dataDelegates[context] = delegateName; - } - }; - - for (var context in g_delegateCallbacks) { - _loop(context); - } - - for (var key in config.data.dataDelegates) { - try { - var delegateName = config.data.dataDelegates[key]; - var DelegateClass = paella.dataDelegates[delegateName]; - var delegateInstance = new DelegateClass(); - g_dataDelegates[key] = delegateInstance; - } catch (e) { - console.warn("Warning: delegate not found - " + delegateName); - } - } // Default data delegate - - - if (!this.dataDelegates["default"]) { - this.dataDelegates["default"] = new paella.dataDelegates.DefaultDataDelegate(); - } - } - - _createClass(Data, [{ - key: "enabled", - get: function get() { - return this._enabled; - } - }, { - key: "dataDelegates", - get: function get() { - return g_dataDelegates; - } - }, { - key: "read", - value: function read(context, key, onSuccess) { - var del = this.getDelegate(context); - del.read(context, key, onSuccess); - } - }, { - key: "write", - value: function write(context, key, params, onSuccess) { - var del = this.getDelegate(context); - del.write(context, key, params, onSuccess); - } - }, { - key: "remove", - value: function remove(context, key, onSuccess) { - var del = this.getDelegate(context); - del.remove(context, key, onSuccess); - } - }, { - key: "getDelegate", - value: function getDelegate(context) { - if (this.dataDelegates[context]) return this.dataDelegates[context];else return this.dataDelegates["default"]; - } - }]); - - return Data; - }(); - - paella.Data = Data; - - paella.addDataDelegate = function (context, callback) { - if (Array.isArray(context)) { - context.forEach(function (ctx) { - g_delegateCallbacks[ctx] = callback; - }); - } else if (typeof context == "string") { - g_delegateCallbacks[context] = callback; - } - }; -})(); - -paella.addDataDelegate(["default", "trimming"], function () { - paella.dataDelegates.DefaultDataDelegate = /*#__PURE__*/function (_paella$DataDelegate) { - _inherits(CookieDataDelegate, _paella$DataDelegate); - - var _super3 = _createSuper(CookieDataDelegate); - - function CookieDataDelegate() { - _classCallCheck(this, CookieDataDelegate); - - return _super3.apply(this, arguments); - } - - _createClass(CookieDataDelegate, [{ - key: "serializeKey", - value: function serializeKey(context, params) { - if (_typeof(params) == 'object') { - params = JSON.stringify(params); - } - - return context + '|' + params; - } - }, { - key: "read", - value: function read(context, params, onSuccess) { - var key = this.serializeKey(context, params); - var value = paella.utils.cookies.get(key); - - try { - value = unescape(value); - value = JSON.parse(value); - } catch (e) {} - - if (typeof onSuccess == 'function') { - onSuccess(value, true); - } - } - }, { - key: "write", - value: function write(context, params, value, onSuccess) { - var key = this.serializeKey(context, params); - - if (_typeof(value) == 'object') { - value = JSON.stringify(value); - } - - value = escape(value); - paella.utils.cookies.set(key, value); - - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }, { - key: "remove", - value: function remove(context, params, onSuccess) { - var key = this.serializeKey(context, params); - - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) == 'object') { - value = JSON.stringify(value); - } - - paella.utils.cookies.set(key, ''); - - if (typeof onSuccess == 'function') { - onSuccess({}, true); - } - } - }]); - - return CookieDataDelegate; - }(paella.DataDelegate); - - return paella.dataDelegates.DefaultDataDelegate; -}); // Will be initialized inmediately after loading config.json, in PaellaPlayer.onLoadConfig() - -paella.data = null; - -(function () { - paella.utils = paella.utils || {}; - - var Dictionary = /*#__PURE__*/function () { - function Dictionary() { - _classCallCheck(this, Dictionary); - - this._dictionary = {}; - } - - _createClass(Dictionary, [{ - key: "addDictionary", - value: function addDictionary(dict) { - for (var key in dict) { - this._dictionary[key] = dict[key]; - } - } - }, { - key: "translate", - value: function translate(key) { - return this._dictionary[key] || key; - } - }, { - key: "currentLanguage", - value: function currentLanguage() { - var lang = navigator.language || window.navigator.userLanguage; - return lang.substr(0, 2).toLowerCase(); - } - }]); - - return Dictionary; - }(); - - paella.utils.dictionary = new Dictionary(); -})(); - -(function () { - var MessageBox = /*#__PURE__*/function () { - function MessageBox() { - var _this2 = this; - - _classCallCheck(this, MessageBox); - - this._messageContainer = null; - $(window).resize(function (event) { - return _this2.adjustTop(); - }); - } - - _createClass(MessageBox, [{ - key: "modalContainerClassName", - get: function get() { - return 'modalMessageContainer'; - } - }, { - key: "frameClassName", - get: function get() { - return 'frameContainer'; - } - }, { - key: "messageClassName", - get: function get() { - return 'messageContainer'; - } - }, { - key: "errorClassName", - get: function get() { - return 'errorContainer'; - } - }, { - key: "currentMessageBox", - get: function get() { - return this._currentMessageBox; - }, - set: function set(m) { - this._currentMessageBox = m; - } - }, { - key: "messageContainer", - get: function get() { - return this._messageContainer; - } - }, { - key: "onClose", - get: function get() { - return this._onClose; - }, - set: function set(c) { - this._onClose = c; - } - }, { - key: "showFrame", - value: function showFrame(src, params) { - var closeButton = true; - var onClose = null; - - if (params) { - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowFrame(src, closeButton, onClose); - } - }, { - key: "doShowFrame", - value: function doShowFrame(src, closeButton, onClose) { - this.onClose = onClose; - $('#playerContainer').addClass("modalVisible"); - - if (this.currentMessageBox) { - this.close(); - } - - var modalContainer = document.createElement('div'); - modalContainer.className = this.modalContainerClassName; - modalContainer.style.position = 'fixed'; - modalContainer.style.top = '0px'; - modalContainer.style.left = '0px'; - modalContainer.style.right = '0px'; - modalContainer.style.bottom = '0px'; - modalContainer.style.zIndex = 999999; - var messageContainer = document.createElement('div'); - messageContainer.className = this.frameClassName; - modalContainer.appendChild(messageContainer); - var iframeContainer = document.createElement('iframe'); - iframeContainer.src = src; - iframeContainer.setAttribute("frameborder", "0"); - iframeContainer.style.width = "100%"; - iframeContainer.style.height = "100%"; - messageContainer.appendChild(iframeContainer); - - if (paella.player && paella.player.isFullScreen()) { - paella.player.mainContainer.appendChild(modalContainer); - } else { - $('body')[0].appendChild(modalContainer); - } - - this.currentMessageBox = modalContainer; - this._messageContainer = messageContainer; - this.adjustTop(); - - if (closeButton) { - this.createCloseButton(); - } - } - }, { - key: "showElement", - value: function showElement(domElement, params) { - var closeButton = true; - var onClose = null; - var className = this.messageClassName; - - if (params) { - className = params.className; - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowElement(domElement, closeButton, className, onClose); - } - }, { - key: "showMessage", - value: function showMessage(message, params) { - var closeButton = true; - var onClose = null; - var className = this.messageClassName; - - if (params) { - className = params.className; - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowMessage(message, closeButton, className, onClose); - } - }, { - key: "doShowElement", - value: function doShowElement(domElement, closeButton, className, onClose) { - this.onClose = onClose; - $('#playerContainer').addClass("modalVisible"); - - if (this.currentMessageBox) { - this.close(); - } - - if (!className) className = this.messageClassName; - var modalContainer = document.createElement('div'); - modalContainer.className = this.modalContainerClassName; - modalContainer.style.position = 'fixed'; - modalContainer.style.top = '0px'; - modalContainer.style.left = '0px'; - modalContainer.style.right = '0px'; - modalContainer.style.bottom = '0px'; - modalContainer.style.zIndex = 999999; - var messageContainer = document.createElement('div'); - messageContainer.className = className; - messageContainer.appendChild(domElement); - modalContainer.appendChild(messageContainer); - $('body')[0].appendChild(modalContainer); - this.currentMessageBox = modalContainer; - this._messageContainer = messageContainer; - this.adjustTop(); - - if (closeButton) { - this.createCloseButton(); - } - } - }, { - key: "doShowMessage", - value: function doShowMessage(message, closeButton, className, onClose) { - this.onClose = onClose; - $('#playerContainer').addClass("modalVisible"); - - if (this.currentMessageBox) { - this.close(); - } - - if (!className) className = this.messageClassName; - var modalContainer = document.createElement('div'); - modalContainer.className = this.modalContainerClassName; - modalContainer.style.position = 'fixed'; - modalContainer.style.top = '0px'; - modalContainer.style.left = '0px'; - modalContainer.style.right = '0px'; - modalContainer.style.bottom = '0px'; - modalContainer.style.zIndex = 999999; - var messageContainer = document.createElement('div'); - messageContainer.className = className; - messageContainer.innerHTML = message; - modalContainer.appendChild(messageContainer); - - if (paella.player && paella.player.isFullScreen()) { - paella.player.mainContainer.appendChild(modalContainer); - } else { - $('body')[0].appendChild(modalContainer); - } - - this.currentMessageBox = modalContainer; - this._messageContainer = messageContainer; - this.adjustTop(); - - if (closeButton) { - this.createCloseButton(); - } - } - }, { - key: "showError", - value: function showError(message, params) { - var closeButton = false; - var onClose = null; - - if (params) { - closeButton = params.closeButton; - onClose = params.onClose; - } - - this.doShowError(message, closeButton, onClose); - } - }, { - key: "doShowError", - value: function doShowError(message, closeButton, onClose) { - this.doShowMessage(message, closeButton, this.errorClassName, onClose); - } - }, { - key: "createCloseButton", - value: function createCloseButton() { - var _this3 = this; - - if (this._messageContainer) { - var closeButton = document.createElement('span'); - - this._messageContainer.appendChild(closeButton); - - closeButton.className = 'paella_messageContainer_closeButton icon-cancel-circle'; - $(closeButton).click(function (event) { - return _this3.onCloseButtonClick(); - }); - $(window).keyup(function (evt) { - if (evt.keyCode == 27) { - _this3.onCloseButtonClick(); - } - }); - } - } - }, { - key: "adjustTop", - value: function adjustTop() { - if (this.currentMessageBox) { - var msgHeight = $(this._messageContainer).outerHeight(); - var containerHeight = $(this.currentMessageBox).height(); - var top = containerHeight / 2 - msgHeight / 2; - this._messageContainer.style.marginTop = top + 'px'; - } - } - }, { - key: "close", - value: function close() { - if (this.currentMessageBox && this.currentMessageBox.parentNode) { - var msgBox = this.currentMessageBox; - var parent = msgBox.parentNode; - $('#playerContainer').removeClass("modalVisible"); - $(msgBox).animate({ - opacity: 0.0 - }, 300, function () { - parent.removeChild(msgBox); - }); - - if (this.onClose) { - this.onClose(); - } - } - } - }, { - key: "onCloseButtonClick", - value: function onCloseButtonClick() { - this.close(); - } - }]); - - return MessageBox; - }(); - - paella.MessageBox = MessageBox; - paella.messageBox = new paella.MessageBox(); -})(); - -(function () { - paella.utils = paella.utils || {}; - paella.utils.cookies = { - set: function set(name, value) { - document.cookie = name + "=" + value; - }, - get: function get(name) { - var i, - x, - y, - ARRcookies = document.cookie.split(";"); - - for (i = 0; i < ARRcookies.length; i++) { - x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); - y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); - x = x.replace(/^\s+|\s+$/g, ""); - - if (x == name) { - return unescape(y); - } - } - } - }; - paella.utils.hashParams = { - extractUrl: function extractUrl() { - var urlOnly = window.location.href; - - if (urlOnly.lastIndexOf('#') >= 0) { - urlOnly = urlOnly.substr(0, urlOnly.lastIndexOf('#')); - } - - return urlOnly; - }, - extractParams: function extractParams() { - var params = window.location.href; - - if (params.lastIndexOf('#') >= 0) { - params = params.substr(window.location.href.lastIndexOf('#')); - } else { - params = ""; - } - - return params; - }, - clear: function clear() { - window.location.href = this.extractUrl() + '#'; - }, - unset: function unset(key) { - var url = location.href; - var lastIndex = url.lastIndexOf('#'); - var urlOnly = this.extractUrl(); - - if (lastIndex >= 0 && lastIndex + 1 < url.length) { - var newParams = ""; - var params = url.substr(url.lastIndexOf('#') + 1); - params = params.split('&'); - - for (var i = 0; i < params.length; ++i) { - var current = params[i]; - var keyValue = current.split('='); - - if (keyValue.length >= 2 && keyValue[0] != key || keyValue.length < 2) { - if (newParams == "") newParams += '#';else newParams += "&"; - newParams += current; - } - } - - if (newParams == "") newParams = "#"; - location.href = urlOnly + newParams; - } - }, - set: function set(key, value) { - if (key && value) { - this.unset(key); - var url = this.extractUrl(); - var params = this.extractParams(); - var result = url; - - if (params.length == 0) { - result += '#' + key + '=' + value; - } else if (params.length == 1) { - result += params + key + '=' + value; - } else { - result += params + "&" + key + '=' + value; - } - - location.href = result; - } - }, - get: function get(key) { - var url = location.href; - var index = url.indexOf("#"); - if (index == -1) return ""; - index = url.indexOf(key, index) + key.length; - - if (url.charAt(index) == "=") { - var result = url.indexOf("&", index); - - if (result == -1) { - result = url.length; - } - - return url.substring(index + 1, result); - } - - return ""; - } - }; - paella.utils.parameters = { - list: null, - parse: function parse() { - if (!this.list) { - var url = window.location.href; - this.list = {}; - - if (/(http|https|file)?:\/\/([a-z0-9.\-_\/\~:]*\?)([a-z0-9.\/\-_\%\=\&]*)\#*/i.test(url)) { - var params = RegExp.$3; - var paramArray = params.split('&'); - this.list = {}; - - for (var i = 0; i < paramArray.length; ++i) { - var keyValue = paramArray[i].split('='); - var key = keyValue[0]; - var value = keyValue.length == 2 ? keyValue[1] : ''; - this.list[key] = value; - } - } - } - }, - get: function get(parameter) { - if (this.list == null) { - this.parse(); - } - - return this.list[parameter]; - }, - extractUrl: function extractUrl() { - var urlOnly = paella.utils.hashParams.extractUrl(); - - if (urlOnly.lastIndexOf('?') >= 0) { - urlOnly = urlOnly.substr(0, urlOnly.lastIndexOf('?')); - } - - return urlOnly; - }, - extractParams: function extractParams() { - // Primero quitar los parámetros hash - var urlAndParams = paella.utils.hashParams.extractUrl(); - var params = urlAndParams; - - if (params.lastIndexOf('?') >= 0) { - params = params.substr(window.location.href.lastIndexOf('?')); - } else { - params = ""; - } - - return params; - }, - // Pasa los parámetros de la URL a hash. Esta acción recargará la página - toHash: function toHash() { - var urlOnly = this.extractUrl(); - var hashParameters = paella.utils.hashParams.extractParams(); - var parameters = this.extractParams(); - var newHashParams = ""; - var result = urlOnly; - - if (parameters.length == 0 || parameters.length == 1) { - result += hashParameters; - } else { - parameters = parameters.substr(1); - parameters = parameters.split('&'); - - for (var i = 0; i < parameters.length; ++i) { - keyValue = parameters[i].split('='); - - if (keyValue.length >= 2 && paella.utils.hashParams.get(keyValue[0]) == '') { - if (hashParameters == "" && newHashParams == "") newHashParams += '#';else newHashParams += '&'; - newHashParams += keyValue[0] + '=' + keyValue[1]; - } - } - - result += hashParameters + newHashParams; - } - - if (location.href != result) { - location.href = result; - } - } - }; -})(); - -(function () { - paella.utils = paella.utils || {}; - - function parseOperatingSystem(userAgentString) { - this.system.MacOS = /Macintosh/.test(userAgentString); - this.system.Windows = /Windows/.test(userAgentString); - this.system.iPhone = /iPhone/.test(userAgentString); - this.system.iPodTouch = /iPod/.test(userAgentString); - this.system.iPad = /iPad/.test(userAgentString) || /FxiOS/.test(userAgentString); - this.system.iOS = this.system.iPhone || this.system.iPad || this.system.iPodTouch; - this.system.Android = /Android/.test(userAgentString); - this.system.Linux = this.system.Android ? false : /Linux/.test(userAgentString); - - if (this.system.MacOS) { - this.system.OSName = "Mac OS X"; - parseMacOSVersion.apply(this, [userAgentString]); - } else if (this.system.Windows) { - this.system.OSName = "Windows"; - parseWindowsVersion.apply(this, [userAgentString]); - } else if (this.system.Linux) { - this.system.OSName = "Linux"; - parseLinuxVersion.apply(this, [userAgentString]); - } else if (this.system.iOS) { - this.system.OSName = "iOS"; - parseIOSVersion.apply(this, [userAgentString]); - } else if (this.system.Android) { - this.system.OSName = "Android"; - parseAndroidVersion.apply(this, [userAgentString]); - } - } - - function parseBrowser(userAgentString) { - // Safari: Version/X.X.X Safari/XXX - // Chrome: Chrome/XX.X.XX.XX Safari/XXX - // Opera: Opera/X.XX - // Firefox: Gecko/XXXXXX Firefox/XX.XX.XX - // Explorer: MSIE X.X - this.browser.Version = {}; - this.browser.Safari = /Version\/([\d\.]+) Safari\//.test(userAgentString); - - if (this.browser.Safari) { - this.browser.Name = "Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Chrome = /Chrome\/([\d\.]+) Safari\//.test(userAgentString) || /Chrome\/([\d\.]+) Electron\//.test(userAgentString); - - if (this.browser.Chrome) { - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } // The attribute this.browser.Chrome will still be true, because it is the same browser after all - - - this.browser.EdgeChromium = /Chrome.*Edg\/([0-9\.]+)/.test(userAgentString); - - if (this.browser.EdgeChromium) { - this.browser.Name = "Edge Chromium"; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Opera = /Opera\/[\d\.]+/.test(userAgentString); - - if (this.browser.Opera) { - this.browser.Name = "Opera"; - this.browser.Vendor = "Opera Software"; - var versionString = /Version\/([\d\.]+)/.test(userAgentString); - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Firefox = /Gecko\/[\d\.]+ Firefox\/([\d\.]+)/.test(userAgentString); - - if (this.browser.Firefox) { - this.browser.Name = "Firefox"; - this.browser.Vendor = "Mozilla Foundation"; - this.browser.Version.versionString = RegExp.$1; - } - - var firefoxIOS = this.browser.Firefox || /FxiOS\/(\d+\.\d+)/.test(userAgentString); - - if (firefoxIOS) { - this.browser.Firefox = true; - this.browser.Name = "Firefox"; - this.browser.Vendor = "Mozilla Foundation"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Edge = /Edge\/(.*)/.test(userAgentString); - - if (this.browser.Edge) { - var result = /Edge\/(.*)/.exec(userAgentString); - this.browser.Name = "Edge"; - this.browser.Chrome = false; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = result[1]; - } - - this.browser.Explorer = /MSIE ([\d\.]+)/.test(userAgentString); - - if (!this.browser.Explorer) { - var re = /\Mozilla\/5.0 \(([^)]+)\) like Gecko/; - var matches = re.exec(userAgentString); - - if (matches) { - re = /rv:(.*)/; - var version = re.exec(matches[1]); - this.browser.Explorer = true; - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - - if (version) { - this.browser.Version.versionString = version[1]; - } else { - this.browser.Version.versionString = "unknown"; - } - } - } else { - this.browser.Name = "Internet Explorer"; - this.browser.Vendor = "Microsoft"; - this.browser.Version.versionString = RegExp.$1; - } - - if (this.system.iOS) { - this.browser.IsMobileVersion = true; - this.browser.MobileSafari = /Version\/([\d\.]+) Mobile/.test(userAgentString); - - if (this.browser.MobileSafari) { - this.browser.Name = "Mobile Safari"; - this.browser.Vendor = "Apple"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Android = false; - } else if (this.system.Android) { - this.browser.IsMobileVersion = true; - this.browser.Android = /Version\/([\d\.]+) Mobile/.test(userAgentString); - - if (this.browser.MobileSafari) { - this.browser.Name = "Android Browser"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } else { - this.browser.Chrome = /Chrome\/([\d\.]+)/.test(userAgentString); - this.browser.Name = "Chrome"; - this.browser.Vendor = "Google"; - this.browser.Version.versionString = RegExp.$1; - } - - this.browser.Safari = false; - } else { - this.browser.IsMobileVersion = false; - } - - parseBrowserVersion.apply(this, [userAgentString]); - } - - function parseBrowserVersion(userAgentString) { - if (/([\d]+)\.([\d]+)\.*([\d]*)/.test(this.browser.Version.versionString)) { - this.browser.Version.major = Number(RegExp.$1); - this.browser.Version.minor = Number(RegExp.$2); - this.browser.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - } - } - - function parseMacOSVersion(userAgentString) { - var versionString = /Mac OS X (\d+_\d+_*\d*)/.test(userAgentString) ? RegExp.$1 : ''; - this.system.Version = {}; // Safari/Chrome - - if (versionString != '') { - if (/(\d+)_(\d+)_*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - } - } // Firefox/Opera - else { - versionString = /Mac OS X (\d+\.\d+\.*\d*)/.test(userAgentString) ? RegExp.$1 : 'Unknown'; - - if (/(\d+)\.(\d+)\.*(\d*)/.test(versionString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - } - } - - if (!this.system.Version.major) { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - - this.system.Version.stringValue = this.system.Version.major + '.' + this.system.Version.minor + '.' + this.system.Version.revision; - - switch (this.system.Version.minor) { - case 0: - this.system.Version.name = "Cheetah"; - break; - - case 1: - this.system.Version.name = "Puma"; - break; - - case 2: - this.system.Version.name = "Jaguar"; - break; - - case 3: - this.system.Version.name = "Panther"; - break; - - case 4: - this.system.Version.name = "Tiger"; - break; - - case 5: - this.system.Version.name = "Leopard"; - break; - - case 6: - this.system.Version.name = "Snow Leopard"; - break; - - case 7: - this.system.Version.name = "Lion"; - break; - - case 8: - this.system.Version.name = "Mountain Lion"; - break; - - case 9: - this.system.Version.name = "Mavericks"; - break; - - case 10: - this.system.Version.name = "Yosemite"; - break; - - case 11: - this.system.Version.name = "El Capitan"; - break; - - case 12: - this.system.Version.name = "Sierra"; - break; - - case 13: - this.system.Version.name = "High Sierra"; - break; - - case 14: - this.system.Version.name = "Mojave"; - break; - - case 15: - this.system.Version.name = "Catalina"; - break; - } - } - - function parseWindowsVersion(userAgentString) { - this.system.Version = {}; - - if (/NT (\d+)\.(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = 0; // Solo por compatibilidad - - this.system.Version.stringValue = "NT " + this.system.Version.major + "." + this.system.Version.minor; - var major = this.system.Version.major; - var minor = this.system.Version.minor; - var name = 'undefined'; - - if (major == 5) { - if (minor == 0) this.system.Version.name = '2000';else this.system.Version.name = 'XP'; - } else if (major == 6) { - if (minor == 0) this.system.Version.name = 'Vista';else if (minor == 1) this.system.Version.name = '7';else if (minor == 2) this.system.Version.name = '8'; - } else if (major == 10) { - this.system.Version.name = "10"; - } - } else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - function parseLinuxVersion(userAgentString) { - // Muchos navegadores no proporcionan información sobre la distribución de linux... no se puede hacer mucho más que esto - this.system.Version = {}; - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - this.system.Version.name = ""; - this.system.Version.stringValue = "Unknown distribution"; - } - - function parseIOSVersion(userAgentString) { - this.system.Version = {}; - - if (/iPhone OS (\d+)_(\d+)_*(\d*)/i.test(userAgentString) || /iPad; CPU OS (\d+)_(\d+)_*(\d*)/i.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - this.system.Version.name = "iOS"; - } else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.name = "Unknown"; - this.system.Version.stringValue = "Unknown"; - } - } - - function parseAndroidVersion(userAgentString) { - this.system.Version = {}; - - if (/Android (\d+)\.(\d+)\.*(\d*)/.test(userAgentString)) { - this.system.Version.major = Number(RegExp.$1); - this.system.Version.minor = Number(RegExp.$2); - this.system.Version.revision = RegExp.$3 ? Number(RegExp.$3) : 0; - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } else { - this.system.Version.major = 0; - this.system.Version.minor = 0; - this.system.Version.revision = 0; - } - - if (/Build\/([a-zA-Z]+)/.test(userAgentString)) { - this.system.Version.name = RegExp.$1; - } else { - this.system.Version.name = "Unknown version"; - } - - this.system.Version.stringValue = this.system.Version.major + "." + this.system.Version.minor + '.' + this.system.Version.revision; - } - - function getInfoString() { - return navigator.userAgent; - } - - var UserAgent = /*#__PURE__*/function () { - function UserAgent() { - var userAgentString = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - - _classCallCheck(this, UserAgent); - - if (!userAgentString) { - userAgentString = navigator.userAgent; - } - - this._system = {}; - this._browser = {}; - parseOperatingSystem.apply(this, [userAgentString]); - parseBrowser.apply(this, [userAgentString]); - } - - _createClass(UserAgent, [{ - key: "system", - get: function get() { - return this._system; - } - }, { - key: "browser", - get: function get() { - return this._browser; - } - }, { - key: "getInfoString", - value: function getInfoString() { - return navigator.userAgent; - } - }, { - key: "infoString", - get: function get() { - navigator.userAgent; - } - }]); - - return UserAgent; - }(); - - paella.UserAgent = UserAgent; - paella.utils.userAgent = new paella.UserAgent(); -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community 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.osedu.org/licenses/ECL-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. -*/ -// Paella Mouse Manager -/////////////////////////////////////////////////////// - - -(function () { - var MouseManager = /*#__PURE__*/function () { - function MouseManager() { - var _this4 = this; - - _classCallCheck(this, MouseManager); - - paella.events.bind('mouseup', function (event) { - return _this4.up(event); - }); - paella.events.bind('mousemove', function (event) { - return _this4.move(event); - }); - paella.events.bind('mouseover', function (event) { - return _this4.over(event); - }); - } - - _createClass(MouseManager, [{ - key: "targetObject", - get: function get() { - return this._targetObject; - }, - set: function set(t) { - this._targetObject = t; - } - }, { - key: "down", - value: function down(targetObject, event) { - this.targetObject = targetObject; - - if (this.targetObject && this.targetObject.down) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.down(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }, { - key: "up", - value: function up(event) { - if (this.targetObject && this.targetObject.up) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.up(event, pageX, pageY); - event.cancelBubble = true; - } - - this.targetObject = null; - return false; - } - }, { - key: "out", - value: function out(event) { - if (this.targetObject && this.targetObject.out) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.out(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }, { - key: "move", - value: function move(event) { - if (this.targetObject && this.targetObject.move) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.move(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }, { - key: "over", - value: function over(event) { - if (this.targetObject && this.targetObject.over) { - var pageX = event.pageX || (event.changedTouches.length > 0 ? event.changedTouches[0].pageX : 0); - var pageY = event.pageY || (event.changedTouches.length > 0 ? event.changedTouches[0].pageY : 0); - this.targetObject.over(event, pageX, pageY); - event.cancelBubble = true; - } - - return false; - } - }]); - - return MouseManager; - }(); - - paella.MouseManager = MouseManager; -})(); // paella.utils -/////////////////////////////////////////////////////// - - -(function initSkinDeps() { - var link = document.createElement('link'); - link.rel = 'stylesheet'; - link.href = paella.baseUrl + 'resources/bootstrap/css/bootstrap.min.css'; - link.type = 'text/css'; - link.media = 'screen'; - link.charset = 'utf-8'; - document.head.appendChild(link); -})(); - -paella.utils = paella.utils || {}; -paella.utils.mouseManager = new paella.MouseManager(); -paella.utils.folders = { - get: function get(folder) { - if (paella.player && paella.player.config && paella.player.config.folders && paella.player.config.folders[folder]) { - return paella.player.config.folders[folder]; - } - - return undefined; - }, - profiles: function profiles() { - return paella.baseUrl + (paella.utils.folders.get("profiles") || "config/profiles"); - }, - resources: function resources() { - return paella.baseUrl + (paella.utils.folders.get("resources") || "resources"); - }, - skins: function skins() { - return paella.baseUrl + (paella.utils.folders.get("skins") || paella.utils.folders.get("resources") + "/style"); - } -}; -paella.utils.styleSheet = { - removeById: function removeById(id) { - var outStyleSheet = $(document.head).find('#' + id)[0]; - - if (outStyleSheet) { - document.head.removeChild(outStyleSheet); - } - }, - remove: function remove(fileName) { - var links = document.head.getElementsByTagName('link'); - - for (var i = 0; i < links.length; ++i) { - if (links[i].href) { - document.head.removeChild(links[i]); - break; - } - } - }, - add: function add(fileName, id) { - var link = document.createElement('link'); - link.rel = 'stylesheet'; - link.href = fileName; - link.type = 'text/css'; - link.media = 'screen'; - link.charset = 'utf-8'; - if (id) link.id = id; - document.head.appendChild(link); - }, - swap: function swap(outFile, inFile) { - this.remove(outFile); - this.add(inFile); - } -}; -paella.utils.skin = { - set: function set(skinName) { - var skinId = 'paellaSkin'; - paella.utils.styleSheet.removeById(skinId); - paella.utils.styleSheet.add(paella.utils.folders.skins() + '/style_' + skinName + '.css'); - paella.utils.cookies.set("skin", skinName); - }, - restore: function restore(defaultSkin) { - var storedSkin = paella.utils.cookies.get("skin"); - - if (storedSkin && storedSkin != "") { - this.set(storedSkin); - } else { - this.set(defaultSkin); - } - } -}; -paella.utils.timeParse = { - timeToSeconds: function timeToSeconds(timeString) { - var hours = 0; - var minutes = 0; - var seconds = 0; - - if (/([0-9]+)h/i.test(timeString)) { - hours = parseInt(RegExp.$1) * 60 * 60; - } - - if (/([0-9]+)m/i.test(timeString)) { - minutes = parseInt(RegExp.$1) * 60; - } - - if (/([0-9]+)s/i.test(timeString)) { - seconds = parseInt(RegExp.$1); - } - - return hours + minutes + seconds; - }, - secondsToTime: function secondsToTime(seconds) { - var hrs = ~~(seconds / 3600); - if (hrs < 10) hrs = '0' + hrs; - var mins = ~~(seconds % 3600 / 60); - if (mins < 10) mins = '0' + mins; - var secs = Math.floor(seconds % 60); - if (secs < 10) secs = '0' + secs; - return hrs + ':' + mins + ':' + secs; - }, - secondsToText: function secondsToText(secAgo) { - // Seconds - if (secAgo <= 1) { - return paella.utils.dictionary.translate("1 second ago"); - } - - if (secAgo < 60) { - return paella.utils.dictionary.translate("{0} seconds ago").replace(/\{0\}/g, secAgo); - } // Minutes - - - var minAgo = Math.round(secAgo / 60); - - if (minAgo <= 1) { - return paella.utils.dictionary.translate("1 minute ago"); - } - - if (minAgo < 60) { - return paella.utils.dictionary.translate("{0} minutes ago").replace(/\{0\}/g, minAgo); - } //Hours - - - var hourAgo = Math.round(secAgo / (60 * 60)); - - if (hourAgo <= 1) { - return paella.utils.dictionary.translate("1 hour ago"); - } - - if (hourAgo < 24) { - return paella.utils.dictionary.translate("{0} hours ago").replace(/\{0\}/g, hourAgo); - } //Days - - - var daysAgo = Math.round(secAgo / (60 * 60 * 24)); - - if (daysAgo <= 1) { - return paella.utils.dictionary.translate("1 day ago"); - } - - if (daysAgo < 24) { - return paella.utils.dictionary.translate("{0} days ago").replace(/\{0\}/g, daysAgo); - } //Months - - - var monthsAgo = Math.round(secAgo / (60 * 60 * 24 * 30)); - - if (monthsAgo <= 1) { - return paella.utils.dictionary.translate("1 month ago"); - } - - if (monthsAgo < 12) { - return paella.utils.dictionary.translate("{0} months ago").replace(/\{0\}/g, monthsAgo); - } //Years - - - var yearsAgo = Math.round(secAgo / (60 * 60 * 24 * 365)); - - if (yearsAgo <= 1) { - return paella.utils.dictionary.translate("1 year ago"); - } - - return paella.utils.dictionary.translate("{0} years ago").replace(/\{0\}/g, yearsAgo); - }, - matterhornTextDateToDate: function matterhornTextDateToDate(mhdate) { - var d = new Date(); - d.setFullYear(parseInt(mhdate.substring(0, 4), 10)); - d.setMonth(parseInt(mhdate.substring(5, 7), 10) - 1); - d.setDate(parseInt(mhdate.substring(8, 10), 10)); - d.setHours(parseInt(mhdate.substring(11, 13), 10)); - d.setMinutes(parseInt(mhdate.substring(14, 16), 10)); - d.setSeconds(parseInt(mhdate.substring(17, 19), 10)); - return d; - } -}; - -paella.utils.objectFromString = function (str) { - var arr = str.split("."); - var fn = window || _this5; - - for (var i = 0, len = arr.length; i < len; i++) { - fn = fn[arr[i]]; - } - - if (typeof fn !== "function") { - throw new Error("constructor not found"); - } - - return fn; -}; - -paella.utils.uuid = function () { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - var r = Math.random() * 16 | 0; - var v = (c == 'x' ? r : r) & 0x3 | 0x8; - return v.toString(16); - }); -}; - -(function () { - var TimerManager = /*#__PURE__*/function () { - function TimerManager() { - _classCallCheck(this, TimerManager); - - this.timerArray = []; - this.lastId = 0; - } - - _createClass(TimerManager, [{ - key: "setupTimer", - value: function setupTimer(timer, time) { - this.lastId++; - timer.timerId = this.lastId; - timer.timeout = time; - this.timerArray[this.lastId] = timer; - timer.jsTimerId = setTimeout("g_timerManager.executeTimerCallback(".concat(this.lastId, ")"), time); - } - }, { - key: "executeTimerCallback", - value: function executeTimerCallback(timerId) { - var timer = this.timerArray[timerId]; - - if (timer && timer.callback) { - timer.callback(timer, timer.params); - } - - if (timer.repeat) { - timer.jsTimerId = setTimeout("g_timerManager.executeTimerCallback(".concat(timer.timerId, ")"), timer.timeout); - } - } - }]); - - return TimerManager; - }(); - - window.g_timerManager = new TimerManager(); - - var Timer = /*#__PURE__*/function () { - function Timer(callback, time, params) { - _classCallCheck(this, Timer); - - this.callback = callback; - this.params = params; - this._repeat = false; - g_timerManager.setupTimer(this, time); - } - - _createClass(Timer, [{ - key: "repeat", - get: function get() { - return this._repeat; - }, - set: function set(r) { - this._repeat = r; - } - }, { - key: "cancel", - value: function cancel() { - clearTimeout(this.jsTimerId); - } - }], [{ - key: "sleep", - value: function sleep(milliseconds) { - var start = new Date().getTime(); - - for (var i = 0; i < 1e7; ++i) { - if (new Date().getTime() - start > milliseconds) { - break; - } - } - } - }]); - - return Timer; - }(); - - paella.utils.Timer = Timer; -})(); - -(function () { - // Include scripts in header - var g_requiredScripts = {}; - - paella.require = function (path) { - if (!g_requiredScripts[path]) { - g_requiredScripts[path] = new Promise(function (resolve, reject) { - paella.utils.ajax.get({ - url: path - }, function (data) { - try { - var _module = { - exports: null - }; - var exports = null; - eval(data); - - if (_module && _module.exports) { - resolve(_module.exports); - } else { - var geval = eval; - geval(data); - resolve(); - } - } catch (err) { - reject(err); - } - }, function (err) { - reject(err); - }); - }); - } - - return g_requiredScripts[path]; - }; - - paella.tabIndex = new ( /*#__PURE__*/function () { - function TabIndexManager() { - _classCallCheck(this, TabIndexManager); - - this._last = 1; - } - - _createClass(TabIndexManager, [{ - key: "next", - get: function get() { - return this._last++; - } - }, { - key: "last", - get: function get() { - return this._last - 1; - } - }, { - key: "tabIndexElements", - get: function get() { - var result = Array.from($('[tabindex]')); // Sort by tabIndex - - result.sort(function (a, b) { - return a.tabIndex - b.tabIndex; - }); - return result; - } - }, { - key: "insertAfter", - value: function insertAfter(target, elements) { - if (target.tabIndex == null || target.tabIndex == -1) { - throw Error("Insert tab index: the target element does not have a valid tabindex."); - } - - var targetIndex = -1; - var newTabIndexElements = this.tabIndexElements; - newTabIndexElements.some(function (elem, i) { - if (elem == target) { - targetIndex = i; - return true; - } - }); - newTabIndexElements.splice.apply(newTabIndexElements, [targetIndex + 1, 0].concat(_toConsumableArray(elements))); - newTabIndexElements.forEach(function (elem, index) { - elem.tabIndex = index; - +1; - }); - this._last = newTabIndexElements.length; - } - }, { - key: "removeTabIndex", - value: function removeTabIndex(elements) { - var _this6 = this; - - Array.from(elements).forEach(function (e) { - e.removeAttribute("tabindex"); - }); - this.tabIndexElements.forEach(function (elem, index) { - elem.tabIndex = index + 1; - _this6._last = elem.tabIndex + 1; - }); - } - }]); - - return TabIndexManager; - }())(); - - paella.URL = /*#__PURE__*/function () { - function PaellaURL(urlText) { - _classCallCheck(this, PaellaURL); - - this._urlText = urlText; - } - - _createClass(PaellaURL, [{ - key: "text", - get: function get() { - return this._urlText; - } - }, { - key: "isAbsolute", - get: function get() { - return new RegExp('^([a-z]+://|//)', 'i').test(this._urlText) || /^\//.test(this._urlText); // We consider that the URLs starting with / are absolute and local to this server - } - }, { - key: "isExternal", - get: function get() { - var thisUrl = new URL(this.absoluteUrl); - var localUrl = new URL(location.href); - return thisUrl.hostname != localUrl.hostname; - } - }, { - key: "absoluteUrl", - get: function get() { - var result = ""; - - if (new RegExp('^([a-z]+://|//)', 'i').test(this._urlText)) { - result = this._urlText; - } else if (/^\//.test(this._urlText)) { - result = "".concat(location.origin).concat(this._urlText); - } else { - var pathname = location.pathname; - - if (pathname.lastIndexOf(".") > pathname.lastIndexOf("/")) { - pathname = pathname.substring(0, pathname.lastIndexOf("/")) + '/'; - } - - result = "".concat(location.origin).concat(pathname).concat(this._urlText); - } - - result = new URL(result).href; - return result; - } - }, { - key: "appendPath", - value: function appendPath(text) { - if (this._urlText.endsWith("/") && text.startsWith("/")) { - this._urlText += text.substring(1, text.length); - } else if (this._urlText.endsWith("/") || text.startsWith("/")) { - this._urlText += text; - } else { - this._urlText += "/" + text; - } - - return this; - } - }]); - - return PaellaURL; - }(); - - var Log = /*#__PURE__*/function () { - function Log() { - _classCallCheck(this, Log); - - this._currentLevel = 0; - var logLevelParam = paella.utils.parameters.get("logLevel"); - logLevelParam = logLevelParam ? logLevelParam : paella.utils.hashParams.get("logLevel"); - logLevelParam = logLevelParam.toLowerCase(); - - switch (logLevelParam) { - case "error": - this.setLevel(this.kLevelError); - break; - - case "warning": - this.setLevel(this.kLevelWarning); - break; - - case "debug": - this.setLevel(this.kLevelDebug); - break; - - case "log": - this.setLevel(this.kLevelLog); - break; - } - } - - _createClass(Log, [{ - key: "kLevelError", - get: function get() { - return 1; - } - }, { - key: "kLevelWarning", - get: function get() { - return 2; - } - }, { - key: "kLevelDebug", - get: function get() { - return 3; - } - }, { - key: "kLevelLog", - get: function get() { - return 4; - } - }, { - key: "logMessage", - value: function logMessage(level, message) { - var prefix = ""; - - if (typeof level == "string") { - message = level; - } else if (level >= paella.log.kLevelError && level <= paella.log.kLevelLog) { - switch (level) { - case paella.log.kLevelError: - prefix = "ERROR: "; - break; - - case paella.log.kLevelWarning: - prefix = "WARNING: "; - break; - - case paella.log.kLevelDebug: - prefix = "DEBUG: "; - break; - - case paella.log.kLevelLog: - prefix = "LOG: "; - break; - } - } - - if (this._currentLevel >= level && console.log) { - console.log(prefix + message); - } - } - }, { - key: "error", - value: function error(message) { - this.logMessage(paella.log.kLevelError, message); - } - }, { - key: "warning", - value: function warning(message) { - this.logMessage(paella.log.kLevelWarning, message); - } - }, { - key: "debug", - value: function debug(message) { - this.logMessage(paella.log.kLevelDebug, message); - } - }, { - key: "log", - value: function log(message) { - this.logMessage(paella.log.kLevelLog, message); - } - }, { - key: "setLevel", - value: function setLevel(level) { - this._currentLevel = level; - } - }]); - - return Log; - }(); - - paella.log = new Log(); -})(); - -paella.AntiXSS = { - htmlEscape: function htmlEscape(str) { - return String(str).replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>'); - }, - htmlUnescape: function htmlUnescape(value) { - return String(value).replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&'); - } -}; - -function paella_DeferredResolved(param) { - return new Promise(function (resolve) { - resolve(param); - }); -} - -function paella_DeferredRejected(param) { - return new Promise(function (resolve, reject) { - reject(param); - }); -} - -function paella_DeferredNotImplemented() { - return paella_DeferredRejected(new Error("not implemented")); -} -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community 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.osedu.org/licenses/ECL-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. -*/ - - -(function () { - var Node = /*#__PURE__*/function () { - function Node(id) { - _classCallCheck(this, Node); - - this._nodeList = {}; - this.identifier = id; - } - - _createClass(Node, [{ - key: "identifier", - get: function get() { - return this._identifier; - }, - set: function set(id) { - this._identifier = id; - } - }, { - key: "nodeList", - get: function get() { - return this._nodeList; - } - }, { - key: "parent", - get: function get() { - return this._parent; - }, - set: function set(p) { - this._parent = p; - } - }, { - key: "addTo", - value: function addTo(parentNode) { - parentNode.addNode(this); - } - }, { - key: "addNode", - value: function addNode(childNode) { - childNode.parent = this; - this.nodeList[childNode.identifier] = childNode; - return childNode; - } - }, { - key: "getNode", - value: function getNode(id) { - return this.nodeList[id]; - } - }, { - key: "removeNode", - value: function removeNode(childNode) { - if (this.nodeList[childNode.identifier]) { - delete this.nodeList[childNode.identifier]; - return true; - } - - return false; - } - }]); - - return Node; - }(); - - paella.Node = Node; - - var DomNode = /*#__PURE__*/function (_paella$Node) { - _inherits(DomNode, _paella$Node); - - var _super4 = _createSuper(DomNode); - - function DomNode(elementType, id, style) { - var _this7; - - _classCallCheck(this, DomNode); - - _this7 = _super4.call(this, id); - _this7._elementType = elementType; - _this7._domElement = document.createElement(elementType); - _this7.domElement.id = id; - if (style) _this7.style = style; - return _this7; - } - - _createClass(DomNode, [{ - key: "domElement", - get: function get() { - return this._domElement; - } - }, { - key: "domElementType", - get: function get() { - return this._elementType; - }, - set: function set(newType) { - this._elementType = newType; - var oldElement = this._domElement; - var parent = oldElement.parentNode; - var newElement = document.createElement(newType); - parent.removeChild(oldElement); - parent.appendChild(newElement); - this._domElement = newElement; - newElement.innerHTML = oldElement.innerHTML; - - for (var i = 0; i < oldElement.attributes.length; ++i) { - var attr = oldElement.attributes[i]; - newElement.setAttribute(attr.name, attr.value); - } - } - }, { - key: "style", - set: function set(s) { - $(this.domElement).css(s); - } - }, { - key: "addNode", - value: function addNode(childNode) { - var returnValue = _get(_getPrototypeOf(DomNode.prototype), "addNode", this).call(this, childNode); - - this.domElement.appendChild(childNode.domElement); - return returnValue; - } - }, { - key: "onresize", - value: function onresize() {} - }, { - key: "removeNode", - value: function removeNode(childNode) { - if (_get(_getPrototypeOf(DomNode.prototype), "removeNode", this).call(this, childNode)) { - this.domElement.removeChild(childNode.domElement); - } - } - }]); - - return DomNode; - }(paella.Node); - - paella.DomNode = DomNode; - - var Button = /*#__PURE__*/function (_paella$DomNode) { - _inherits(Button, _paella$DomNode); - - var _super5 = _createSuper(Button); - - function Button(id, className, action, isToggle) { - var _this8; - - _classCallCheck(this, Button); - - var style = {}; - _this8 = _super5.call(this, 'div', id, style); - _this8.isToggle = isToggle; - _this8.domElement.className = className; - - if (isToggle) { - $(_this8.domElement).click(function (event) { - _this8.toggleIcon(); - }); - } - - $(_this8.domElement).click('click', action); - return _this8; - } - - _createClass(Button, [{ - key: "isToggle", - get: function get() { - return this._isToggle; - }, - set: function set(t) { - this._isToggle = t; - } - }, { - key: "isToggled", - value: function isToggled() { - if (this.isToggle) { - var element = this.domElement; - return /([a-zA-Z0-9_]+)_active/.test(element.className); - } else { - return false; - } - } - }, { - key: "toggle", - value: function toggle() { - this.toggleIcon(); - } - }, { - key: "toggleIcon", - value: function toggleIcon() { - var element = this.domElement; - - if (/([a-zA-Z0-9_]+)_active/.test(element.className)) { - element.className = RegExp.$1; - } else { - element.className = element.className + '_active'; - } - } - }, { - key: "show", - value: function show() { - $(this.domElement).show(); - } - }, { - key: "hide", - value: function hide() { - $(this.domElement).hide(); - } - }, { - key: "visible", - value: function visible() { - return this.domElement.visible(); - } - }]); - - return Button; - }(paella.DomNode); - - paella.Button = Button; -})(); - -(function () { - var g_profiles = []; - - paella.addProfile = function (cb) { - cb().then(function (profileData) { - if (profileData) { - g_profiles.push(profileData); - - if (typeof profileData.onApply != "function") { - profileData.onApply = function () {}; - } - - if (typeof profileData.onDeactivte != "function") { - profileData.onDeactivate = function () {}; - } - - paella.events.trigger(paella.events.profileListChanged, { - profileData: profileData - }); - } - }); - }; // Utility functions - - - function hideBackground() { - var bkgNode = this.container.getNode("videoContainerBackground"); - if (bkgNode) this.container.removeNode(bkgNode); - } - - function showBackground(bkgData) { - if (!bkgData) return; - hideBackground.apply(this); - this.backgroundData = bkgData; - var style = { - backgroundImage: "url(".concat(paella.baseUrl).concat(paella.utils.folders.get("resources"), "/style/").concat(bkgData.content, ")"), - backgroundSize: "100% 100%", - zIndex: bkgData.layer, - position: 'absolute', - left: bkgData.rect.left + "px", - right: bkgData.rect.right + "px", - width: "100%", - height: "100%" - }; - this.container.addNode(new paella.DomNode('div', "videoContainerBackground", style)); - } - - function hideAllLogos() { - if (this.logos == undefined) return; - - for (var i = 0; i < this.logos.length; ++i) { - var logoId = this.logos[i].content.replace(/\./ig, "-"); - var logo = this.container.getNode(logoId); - $(logo.domElement).hide(); - } - } - - function showLogos(logos) { - this.logos = logos; - var relativeSize = new paella.RelativeVideoSize(); - - for (var i = 0; i < logos.length; ++i) { - var logo = logos[i]; - var logoId = logo.content.replace(/\./ig, "-"); - var logoNode = this.container.getNode(logoId); - var rect = logo.rect; - - if (!logoNode) { - style = {}; - logoNode = this.container.addNode(new paella.DomNode('img', logoId, style)); - logoNode.domElement.setAttribute('src', "".concat(paella.baseUrl).concat(paella.utils.folders.get("resources"), "/style/").concat(logo.content)); - } else { - $(logoNode.domElement).show(); - } - - var percentTop = Number(relativeSize.percentVSize(rect.top)) + '%'; - var percentLeft = Number(relativeSize.percentWSize(rect.left)) + '%'; - var percentWidth = Number(relativeSize.percentWSize(rect.width)) + '%'; - var percentHeight = Number(relativeSize.percentVSize(rect.height)) + '%'; - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute', - zIndex: logo.zIndex - }; - $(logoNode.domElement).css(style); - } - } - - function hideButtons() { - var _this9 = this; - - if (this.buttons) { - this.buttons.forEach(function (btn) { - _this9.container.removeNode(_this9.container.getNode(btn.id)); - }); - this.buttons = null; - } - } - - function showButtons(buttons, profileData) { - var _this10 = this; - - hideButtons.apply(this); - - if (buttons) { - var relativeSize = new paella.RelativeVideoSize(); - this.buttons = buttons; - buttons.forEach(function (btn, index) { - btn.id = "button_" + index; - var rect = btn.rect; - var percentTop = relativeSize.percentVSize(rect.top) + '%'; - var percentLeft = relativeSize.percentWSize(rect.left) + '%'; - var percentWidth = relativeSize.percentWSize(rect.width) + '%'; - var percentHeight = relativeSize.percentVSize(rect.height) + '%'; - var url = paella.baseUrl; - url = url.replace(/\\/ig, '/'); - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute', - zIndex: btn.layer, - backgroundImage: "url(".concat(paella.baseUrl).concat(paella.utils.folders.get("resources"), "/style/").concat(btn.icon, ")"), - backgroundSize: '100% 100%', - display: 'block' - }; - - var logoNode = _this10.container.addNode(new paella.DomNode('div', btn.id, style)); - - logoNode.domElement.className = "paella-profile-button"; - logoNode.domElement.data = { - action: btn.onClick, - profileData: profileData - }; - $(logoNode.domElement).click(function (evt) { - this.data.action.apply(this.data.profileData, [evt]); - evt.stopPropagation(); - return false; - }); - }); - } - } - - function getClosestRect(profileData, videoDimensions) { - var minDiff = 10; - var re = /([0-9\.]+)\/([0-9\.]+)/; - var result = profileData.rect[0]; - var videoAspectRatio = videoDimensions.h == 0 ? 1.777777 : videoDimensions.w / videoDimensions.h; - var profileAspectRatio = 1; - var reResult = false; - profileData.rect.forEach(function (rect) { - if (reResult = re.exec(rect.aspectRatio)) { - profileAspectRatio = Number(reResult[1]) / Number(reResult[2]); - } - - var diff = Math.abs(profileAspectRatio - videoAspectRatio); - - if (minDiff > diff) { - minDiff = diff; - result = rect; - } - }); - return result; - } - - function applyProfileWithJson(profileData, animate) { - var _this11 = this; - - if (animate == undefined) animate = true; - if (!profileData) return; - - var getProfile = function getProfile(content) { - var result = null; - profileData && profileData.videos.some(function (videoProfile) { - if (videoProfile.content == content) { - result = videoProfile; - } - - return result != null; - }); - return result; - }; - - var applyVideoRect = function applyVideoRect(profile, videoData, videoWrapper, player) { - var frameStrategy = _this11.profileFrameStrategy; - - if (frameStrategy) { - var rect = getClosestRect(profile, videoData.res); - var videoSize = videoData.res; - var containerSize = { - width: $(_this11.domElement).width(), - height: $(_this11.domElement).height() - }; - var scaleFactor = rect.width / containerSize.width; - var scaledVideoSize = { - width: videoSize.w * scaleFactor, - height: videoSize.h * scaleFactor - }; - rect.left = Number(rect.left); - rect.top = Number(rect.top); - rect.width = Number(rect.width); - rect.height = Number(rect.height); - rect = frameStrategy.adaptFrame(scaledVideoSize, rect); - var visible = /true/i.test(profile.visible); - rect.visible = visible; - var layer = parseInt(profile.layer); - videoWrapper.domElement.style.zIndex = layer; - videoWrapper.setRect(rect, animate); - videoWrapper.setVisible(visible, animate); // The disable/enable functions may not be called on main audio player - - var isMainAudioPlayer = paella.player.videoContainer.streamProvider.mainAudioPlayer == player; - visible ? player.enable(isMainAudioPlayer) : player.disable(isMainAudioPlayer); - } - }; - - profileData && profileData.onApply(); - hideAllLogos.apply(this); - profileData && showLogos.apply(this, [profileData.logos]); - hideBackground.apply(this); - profileData && showBackground.apply(this, [profileData.background]); - hideButtons.apply(this); - profileData && showButtons.apply(this, [profileData.buttons, profileData]); - this.streamProvider.videoStreams.forEach(function (streamData, index) { - var profile = getProfile(streamData.content); - var player = _this11.streamProvider.videoPlayers[index]; - var videoWrapper = _this11.videoWrappers[index]; - - if (profile) { - player.getVideoData().then(function (data) { - applyVideoRect(profile, data, videoWrapper, player); - }); - } else if (videoWrapper) { - videoWrapper.setVisible(false, animate); - player.disable(paella.player.videoContainer.streamProvider.mainAudioPlayer == player); - } - }); - } - - var profileReloadCount = 0; - var maxProfileReloadCunt = 20; - - var Profiles = /*#__PURE__*/function () { - function Profiles() { - var _this12 = this; - - _classCallCheck(this, Profiles); - - paella.events.bind(paella.events.controlBarDidHide, function () { - return _this12.hideButtons(); - }); - paella.events.bind(paella.events.controlBarDidShow, function () { - return _this12.showButtons(); - }); - paella.events.bind(paella.events.profileListChanged, function () { - if (paella.player && paella.player.videoContainer && (!_this12.currentProfile || _this12.currentProfileName != _this12.currentProfile.id)) { - _this12.setProfile(_this12.currentProfileName, false); - } - }); - } - - _createClass(Profiles, [{ - key: "profileList", - get: function get() { - return g_profiles; - } - }, { - key: "getDefaultProfile", - value: function getDefaultProfile() { - if (paella.player.videoContainer.masterVideo() && paella.player.videoContainer.masterVideo().defaultProfile()) { - return paella.player.videoContainer.masterVideo().defaultProfile(); - } - - if (paella.player && paella.player.config && paella.player.config.defaultProfile) { - return paella.player.config.defaultProfile; - } - - return undefined; - } - }, { - key: "loadProfile", - value: function loadProfile(profileId) { - var result = null; - g_profiles.some(function (profile) { - if (profile.id == profileId) { - result = profile; - } - - return result; - }); - return result; - } - }, { - key: "currentProfile", - get: function get() { - return this.getProfile(this._currentProfileName); - } - }, { - key: "currentProfileName", - get: function get() { - return this._currentProfileName; - } - }, { - key: "setProfile", - value: function setProfile(profileName, animate) { - var _this13 = this; - - if (!profileName) { - return false; - } - - animate = paella.utils.userAgent.browser.Explorer ? false : animate; - - if (this.currentProfile) { - this.currentProfile.onDeactivate(); - } - - if (!paella.player.videoContainer.ready) { - return false; // Nothing to do, the video is not loaded - } else { - var profileData = this.loadProfile(profileName) || g_profiles.length > 0 && g_profiles[0]; - - if (!profileData && g_profiles.length == 0) { - if (profileReloadCount < maxProfileReloadCunt) { - profileReloadCount++; // Try to load the profile again later, maybe the profiles are not loaded yet - - setTimeout(function () { - _this13.setProfile(profileName, animate); - }, 100); - return false; - } else { - console.error("No valid video layout profiles were found. Check that the 'content' attribute setting in 'videoSets', at config.json file, matches the 'content' property in the video manifest."); - return false; - } - } else { - this._currentProfileName = profileName; - applyProfileWithJson.apply(paella.player.videoContainer, [profileData, animate]); - return true; - } - } - } - }, { - key: "getProfile", - value: function getProfile(profileName) { - var result = null; - this.profileList.some(function (p) { - if (p.id == profileName) { - result = p; - return true; - } - }); - return result; - } - }, { - key: "placeVideos", - value: function placeVideos() { - this.setProfile(this._currentProfileName, false); - } - }, { - key: "hideButtons", - value: function hideButtons() { - $('.paella-profile-button').hide(); - } - }, { - key: "showButtons", - value: function showButtons() { - $('.paella-profile-button').show(); - } - }]); - - return Profiles; - }(); - - paella.profiles = new Profiles(); -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community 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.osedu.org/licenses/ECL-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. -*/ - - -(function () { - var VideoQualityStrategy = /*#__PURE__*/function () { - function VideoQualityStrategy() { - _classCallCheck(this, VideoQualityStrategy); - } - - _createClass(VideoQualityStrategy, [{ - key: "getParams", - value: function getParams() { - return paella.player.config.player.videoQualityStrategyParams || {}; - } - }, { - key: "getQualityIndex", - value: function getQualityIndex(source) { - if (source.length > 0) { - return source[source.length - 1]; - } else { - return source; - } - } - }], [{ - key: "Factory", - value: function Factory() { - var config = paella.player.config; - - try { - var strategyClass = config.player.videoQualityStrategy; - var ClassObject = paella.utils.objectFromString(strategyClass); - var strategy = new ClassObject(); - - if (strategy instanceof paella.VideoQualityStrategy) { - return strategy; - } - } catch (e) {} - - return null; - } - }]); - - return VideoQualityStrategy; - }(); - - paella.VideoQualityStrategy = VideoQualityStrategy; - - var BestFitVideoQualityStrategy = /*#__PURE__*/function (_paella$VideoQualityS) { - _inherits(BestFitVideoQualityStrategy, _paella$VideoQualityS); - - var _super6 = _createSuper(BestFitVideoQualityStrategy); - - function BestFitVideoQualityStrategy() { - _classCallCheck(this, BestFitVideoQualityStrategy); - - return _super6.apply(this, arguments); - } - - _createClass(BestFitVideoQualityStrategy, [{ - key: "getQualityIndex", - value: function getQualityIndex(source) { - var index = source.length - 1; - - if (source.length > 0) { - var selected = source[0]; - var win_w = $(window).width(); - var win_h = $(window).height(); - var win_res = win_w * win_h; - - if (selected.res && selected.res.w && selected.res.h) { - var selected_res = parseInt(selected.res.w) * parseInt(selected.res.h); - var selected_diff = Math.abs(win_res - selected_res); - - for (var i = 0; i < source.length; ++i) { - var res = source[i].res; - - if (res) { - var m_res = parseInt(source[i].res.w) * parseInt(source[i].res.h); - var m_diff = Math.abs(win_res - m_res); - - if (m_diff <= selected_diff) { - selected_diff = m_diff; - index = i; - } - } - } - } - } - - return index; - } - }]); - - return BestFitVideoQualityStrategy; - }(paella.VideoQualityStrategy); - - paella.BestFitVideoQualityStrategy = BestFitVideoQualityStrategy; - - var LimitedBestFitVideoQualityStrategy = /*#__PURE__*/function (_paella$VideoQualityS2) { - _inherits(LimitedBestFitVideoQualityStrategy, _paella$VideoQualityS2); - - var _super7 = _createSuper(LimitedBestFitVideoQualityStrategy); - - function LimitedBestFitVideoQualityStrategy() { - _classCallCheck(this, LimitedBestFitVideoQualityStrategy); - - return _super7.apply(this, arguments); - } - - _createClass(LimitedBestFitVideoQualityStrategy, [{ - key: "getQualityIndex", - value: function getQualityIndex(source) { - var index = source.length - 1; - var params = this.getParams(); - - if (source.length > 0) { - //var selected = source[0]; - var selected = null; - var win_h = $(window).height(); - var maxRes = params.maxAutoQualityRes || 720; - var diff = Number.MAX_VALUE; - source.forEach(function (item, i) { - if (item.res && item.res.h <= maxRes) { - var itemDiff = Math.abs(win_h - item.res.h); - - if (itemDiff < diff) { - selected = item; - index = i; - } - } - }); - } - - return index; - } - }]); - - return LimitedBestFitVideoQualityStrategy; - }(paella.VideoQualityStrategy); - - paella.LimitedBestFitVideoQualityStrategy = LimitedBestFitVideoQualityStrategy; - - var VideoFactory = /*#__PURE__*/function () { - function VideoFactory() { - _classCallCheck(this, VideoFactory); - } - - _createClass(VideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return false; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - return null; - } - }]); - - return VideoFactory; - }(); - - paella.VideoFactory = VideoFactory; - paella.videoFactories = paella.videoFactories || {}; - paella.videoFactory = { - _factoryList: [], - initFactories: function initFactories() { - if (paella.videoFactories) { - var This = this; - paella.player.config.player.methods.forEach(function (method) { - if (method.enabled && paella.videoFactories[method.factory]) { - This.registerFactory(new paella.videoFactories[method.factory]()); - } - }); - this.registerFactory(new paella.videoFactories.EmptyVideoFactory()); - } - }, - getVideoObject: function getVideoObject(id, streamData, rect) { - if (this._factoryList.length == 0) { - this.initFactories(); - } - - var selectedFactory = null; - - if (this._factoryList.some(function (factory) { - if (factory.isStreamCompatible(streamData)) { - selectedFactory = factory; - return true; - } - })) { - return selectedFactory.getVideoObject(id, streamData, rect); - } - - return null; - }, - registerFactory: function registerFactory(factory) { - this._factoryList.push(factory); - } - }; -})(); - -(function () { - var AudioElementBase = /*#__PURE__*/function (_paella$DomNode2) { - _inherits(AudioElementBase, _paella$DomNode2); - - var _super8 = _createSuper(AudioElementBase); - - function AudioElementBase(id, stream) { - var _this14; - - _classCallCheck(this, AudioElementBase); - - _this14 = _super8.call(this, 'div', id); - _this14._stream = stream; - _this14._ready = false; - return _this14; - } - - _createClass(AudioElementBase, [{ - key: "ready", - get: function get() { - return this._ready; - } - }, { - key: "currentTimeSync", - get: function get() { - return null; - } - }, { - key: "volumeSync", - get: function get() { - return null; - } - }, { - key: "pausedSync", - get: function get() { - return null; - } - }, { - key: "durationSync", - get: function get() { - return null; - } - }, { - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "setAutoplay", - value: function setAutoplay() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "load", - value: function load() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "play", - value: function play() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "pause", - value: function pause() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "isPaused", - value: function isPaused() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "duration", - value: function duration() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "currentTime", - value: function currentTime() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "volume", - value: function volume() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "playbackRate", - value: function playbackRate() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "unload", - value: function unload() { - return Promise.reject(new Error("no such compatible video player")); - } - }, { - key: "getQualities", - value: function getQualities() { - return Promise.resolve([{ - index: 0, - res: { - w: 0, - h: 1 - }, - src: "", - toString: function toString() { - return ""; - }, - shortLabel: function shortLabel() { - return ""; - }, - compare: function compare() { - return 0; - } - }]); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - return Promise.resolve(0); - } - }, { - key: "defaultProfile", - value: function defaultProfile() { - return null; - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return false; - } - }]); - - return AudioElementBase; - }(paella.DomNode); - - ; - paella.AudioElementBase = AudioElementBase; - paella.audioFactories = {}; - - var AudioFactory = /*#__PURE__*/function () { - function AudioFactory() { - _classCallCheck(this, AudioFactory); - } - - _createClass(AudioFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return false; - } - }, { - key: "getAudioObject", - value: function getAudioObject(id, streamData) { - return null; - } - }]); - - return AudioFactory; - }(); - - paella.AudioFactory = AudioFactory; - paella.audioFactory = { - _factoryList: [], - initFactories: function initFactories() { - if (paella.audioFactories) { - var This = this; - paella.player.config.player.audioMethods = paella.player.config.player.audioMethods || {}; - paella.player.config.player.audioMethods.forEach(function (method) { - if (method.enabled) { - This.registerFactory(new paella.audioFactories[method.factory]()); - } - }); - } - }, - getAudioObject: function getAudioObject(id, streamData) { - if (this._factoryList.length == 0) { - this.initFactories(); - } - - var selectedFactory = null; - - if (this._factoryList.some(function (factory) { - if (factory.isStreamCompatible(streamData)) { - selectedFactory = factory; - return true; - } - })) { - return selectedFactory.getAudioObject(id, streamData); - } - - return null; - }, - registerFactory: function registerFactory(factory) { - this._factoryList.push(factory); - } - }; -})(); - -(function () { - function checkReady(cb) { - var This = this; - return new Promise(function (resolve, reject) { - if (This._ready) { - resolve(typeof cb == 'function' ? cb() : true); - } else { - function doCheck() { - if (This.audio.readyState >= This.audio.HAVE_CURRENT_DATA) { - This._ready = true; - resolve(typeof cb == 'function' ? cb() : true); - } else { - setTimeout(doCheck, 50); - } - } - - doCheck(); - } - }); - } - - var MultiformatAudioElement = /*#__PURE__*/function (_paella$AudioElementB) { - _inherits(MultiformatAudioElement, _paella$AudioElementB); - - var _super9 = _createSuper(MultiformatAudioElement); - - function MultiformatAudioElement(id, stream) { - var _this15; - - _classCallCheck(this, MultiformatAudioElement); - - _this15 = _super9.call(this, id, stream); - _this15._streamName = "audio"; - _this15._audio = document.createElement('audio'); - - _this15.domElement.appendChild(_this15._audio); - - return _this15; - } - - _createClass(MultiformatAudioElement, [{ - key: "buffered", - get: function get() { - return this.audio && this.audio.buffered; - } - }, { - key: "audio", - get: function get() { - return this._audio; - } - }, { - key: "currentTimeSync", - get: function get() { - return this.ready ? this.audio.currentTimeSync : null; - } - }, { - key: "volumeSync", - get: function get() { - return this.ready ? this.audio.volumeSync : null; - } - }, { - key: "pausedSync", - get: function get() { - return this.ready ? this.audio.pausedSync : null; - } - }, { - key: "durationSync", - get: function get() { - return this.ready ? this.audio.durationSync : null; - } - }, { - key: "setAutoplay", - value: function setAutoplay(ap) { - this.audio.autoplay = ap; - } - }, { - key: "load", - value: function load() { - var This = this; - var sources = this._stream.sources[this._streamName]; - var stream = sources.length > 0 ? sources[0] : null; - this.audio.innerText = ""; - - if (stream) { - var sourceElem = this.audio.querySelector('source'); - - if (!sourceElem) { - sourceElem = document.createElement('source'); - this.audio.appendChild(sourceElem); - } - - sourceElem.src = stream.src; - if (stream.type) sourceElem.type = stream.type; - this.audio.load(); - return checkReady.apply(this, [function () { - return stream; - }]); - } else { - return Promise.reject(new Error("Could not load video: invalid quality stream index")); - } - } - }, { - key: "play", - value: function play() { - var _this16 = this; - - return checkReady.apply(this, [function () { - _this16.audio.play(); - }]); - } - }, { - key: "pause", - value: function pause() { - var _this17 = this; - - return checkReady.apply(this, [function () { - _this17.audio.pause(); - }]); - } - }, { - key: "isPaused", - value: function isPaused() { - var _this18 = this; - - return checkReady.apply(this, [function () { - return _this18.audio.paused; - }]); - } - }, { - key: "duration", - value: function duration() { - var _this19 = this; - - return checkReady.apply(this, [function () { - return _this19.audio.duration; - }]); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this20 = this; - - return checkReady.apply(this, [function () { - _this20.audio.currentTime = time; - }]); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this21 = this; - - return checkReady.apply(this, [function () { - return _this21.audio.currentTime; - }]); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - var _this22 = this; - - return checkReady.apply(this, [function () { - return _this22.audio.volume = volume; - }]); - } - }, { - key: "volume", - value: function volume() { - var _this23 = this; - - return checkReady.apply(this, [function () { - return _this23.audio.volume; - }]); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - var _this24 = this; - - return checkReady.apply(this, [function () { - _this24.audio.playbackRate = rate; - }]); - } - }, { - key: "playbackRate", - value: function playbackRate() { - var _this25 = this; - - return checkReady.apply(this, [function () { - return _this25.audio.playbackRate; - }]); - } - }, { - key: "unload", - value: function unload() { - return Promise.resolve(); - } - }]); - - return MultiformatAudioElement; - }(paella.AudioElementBase); - - ; - paella.MultiformatAudioElement = MultiformatAudioElement; - - var MultiformatAudioFactory = /*#__PURE__*/function () { - function MultiformatAudioFactory() { - _classCallCheck(this, MultiformatAudioFactory); - } - - _createClass(MultiformatAudioFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return true; - } - }, { - key: "getAudioObject", - value: function getAudioObject(id, streamData) { - return new paella.MultiformatAudioElement(id, streamData); - } - }]); - - return MultiformatAudioFactory; - }(); - - paella.audioFactories.MultiformatAudioFactory = MultiformatAudioFactory; -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community 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.osedu.org/licenses/ECL-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. -*/ - - -(function () { - paella.Profiles = { - profileList: null, - getDefaultProfile: function getDefaultProfile() { - if (paella.player.videoContainer.masterVideo() && paella.player.videoContainer.masterVideo().defaultProfile()) { - return paella.player.videoContainer.masterVideo().defaultProfile(); - } - - if (paella.player && paella.player.config && paella.player.config.defaultProfile) { - return paella.player.config.defaultProfile; - } - - return undefined; - }, - loadProfile: function loadProfile(profileName, onSuccessFunction) { - var defaultProfile = this.getDefaultProfile(); - this.loadProfileList(function (data) { - var profileData; - - if (data[profileName]) { - // Successful mapping - profileData = data[profileName]; - } else if (data[defaultProfile]) { - // Fallback to default profile - profileData = data[defaultProfile]; - } else { - // Unable to find or map defaultProfile in profiles.json - paella.log.debug("Error loading the default profile. Check your Paella Player configuration"); - return false; - } - - onSuccessFunction(profileData); - }); - }, - loadProfileList: function loadProfileList(onSuccessFunction) { - var thisClass = this; - - if (this.profileList == null) { - var params = { - url: paella.utils.folders.profiles() + "/profiles.json" - }; - paella.utils.ajax.get(params, function (data, mimetype, code) { - if (typeof data == "string") { - data = JSON.parse(data); - } - - thisClass.profileList = data; - onSuccessFunction(thisClass.profileList); - }, function (data, mimetype, code) { - paella.log.debug("Error loading video profiles. Check your Paella Player configuration"); - }); - } else { - onSuccessFunction(thisClass.profileList); - } - } - }; - - var RelativeVideoSize = /*#__PURE__*/function () { - function RelativeVideoSize() { - _classCallCheck(this, RelativeVideoSize); - } - - _createClass(RelativeVideoSize, [{ - key: "w", - get: function get() { - return this._w || 1280; - }, - set: function set(v) { - this._w = v; - } - }, { - key: "h", - get: function get() { - return this._h || 720; - }, - set: function set(v) { - this._h = v; - } - }, { - key: "proportionalHeight", - value: function proportionalHeight(newWidth) { - return Math.floor(this.h * newWidth / this.w); - } - }, { - key: "proportionalWidth", - value: function proportionalWidth(newHeight) { - return Math.floor(this.w * newHeight / this.h); - } - }, { - key: "percentVSize", - value: function percentVSize(pxSize) { - return pxSize * 100 / this.h; - } - }, { - key: "percentWSize", - value: function percentWSize(pxSize) { - return pxSize * 100 / this.w; - } - }, { - key: "aspectRatio", - value: function aspectRatio() { - return this.w / this.h; - } - }]); - - return RelativeVideoSize; - }(); - - paella.RelativeVideoSize = RelativeVideoSize; - - var VideoRect = /*#__PURE__*/function (_paella$DomNode3) { - _inherits(VideoRect, _paella$DomNode3); - - var _super10 = _createSuper(VideoRect); - - function VideoRect(id, domType, left, top, width, height) { - var _this26; - - _classCallCheck(this, VideoRect); - - _this26 = _super10.call(this, domType, id, {}); - var zoomSettings = paella.player.config.player.videoZoom || {}; - - var zoomEnabled = (zoomSettings.enabled !== undefined ? zoomSettings.enabled : true) && _this26.allowZoom(); - - _this26.style = zoomEnabled ? { - width: _this26._zoom + '%', - height: "100%", - position: 'absolute' - } : { - width: "100%", - height: "100%" - }; - _this26._rect = null; - var eventCapture = document.createElement('div'); - setTimeout(function () { - return _this26.domElement.parentElement.appendChild(eventCapture); - }, 10); - eventCapture.id = id + "EventCapture"; - eventCapture.style.position = "absolute"; - eventCapture.style.top = "0px"; - eventCapture.style.left = "0px"; - eventCapture.style.right = "0px"; - eventCapture.style.bottom = "0px"; - _this26.eventCapture = eventCapture; - - if (zoomEnabled) { - _this26._zoomAvailable = true; - - function checkZoomAvailable() { - var minWindowSize = paella.player.config.player && paella.player.config.player.videoZoom && paella.player.config.player.videoZoom.minWindowSize || 500; - var available = $(window).width() >= minWindowSize; - - if (this._zoomAvailable != available) { - this._zoomAvailable = available; - paella.events.trigger(paella.events.zoomAvailabilityChanged, { - available: available - }); - } - } - - checkZoomAvailable.apply(_assertThisInitialized(_this26)); - $(window).resize(function () { - checkZoomAvailable.apply(_assertThisInitialized(_this26)); - }); - _this26._zoom = 100; - _this26._mouseCenter = { - x: 0, - y: 0 - }; - _this26._mouseDown = { - x: 0, - y: 0 - }; - _this26._zoomOffset = { - x: 0, - y: 0 - }; - _this26._maxZoom = zoomSettings.max || 400; - $(_this26.domElement).css({ - width: "100%", - height: "100%", - left: "0%", - top: "0%" - }); - Object.defineProperty(_assertThisInitialized(_this26), 'zoom', { - get: function get() { - return this._zoom; - } - }); - Object.defineProperty(_assertThisInitialized(_this26), 'zoomOffset', { - get: function get() { - return this._zoomOffset; - } - }); - - function mousePos(evt) { - return { - x: evt.originalEvent.offsetX, - y: evt.originalEvent.offsetY - }; - } - - function wheelDelta(evt) { - var wheel = evt.originalEvent.deltaY * (paella.utils.userAgent.Firefox ? 2 : 1); - var maxWheel = 6; - return -Math.abs(wheel) < maxWheel ? wheel : maxWheel * Math.sign(wheel); - } - - function touchesLength(p0, p1) { - return Math.sqrt((p1.x - p0.x) * (p1.x - p0.x) + (p1.y - p0.y) * (p1.y - p0.y)); - } - - function centerPoint(p0, p1) { - return { - x: (p1.x - p0.x) / 2 + p0.x, - y: (p1.y - p0.y) / 2 + p0.y - }; - } - - function panImage(o) { - var center = { - x: this._mouseCenter.x - o.x * 1.1, - y: this._mouseCenter.y - o.y * 1.1 - }; - var videoSize = { - w: $(this.domElement).width(), - h: $(this.domElement).height() - }; - var maxOffset = this._zoom - 100; - var offset = { - x: center.x * maxOffset / videoSize.w * (maxOffset / 100), - y: center.y * maxOffset / videoSize.h * (maxOffset / 100) - }; - - if (offset.x > maxOffset) { - offset.x = maxOffset; - } else if (offset.x < 0) { - offset.x = 0; - } else { - this._mouseCenter.x = center.x; - } - - if (offset.y > maxOffset) { - offset.y = maxOffset; - } else if (offset.y < 0) { - offset.y = 0; - } else { - this._mouseCenter.y = center.y; - } - - $(this.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - this._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: this - }); - } - - var touches = []; - $(eventCapture).on('touchstart', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - touches = []; - var videoOffset = $(_this26.domElement).offset(); - - for (var i = 0; i < evt.originalEvent.targetTouches.length; ++i) { - var touch = evt.originalEvent.targetTouches[i]; - touches.push({ - x: touch.screenX - videoOffset.left, - y: touch.screenY - videoOffset.top - }); - } - - if (touches.length > 1) evt.preventDefault(); - }); - $(eventCapture).on('touchmove', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - var curTouches = []; - var videoOffset = $(_this26.domElement).offset(); - - for (var i = 0; i < evt.originalEvent.targetTouches.length; ++i) { - var touch = evt.originalEvent.targetTouches[i]; - curTouches.push({ - x: touch.screenX - videoOffset.left, - y: touch.screenY - videoOffset.top - }); - } - - if (curTouches.length > 1 && touches.length > 1) { - var l0 = touchesLength(touches[0], touches[1]); - var l1 = touchesLength(curTouches[0], curTouches[1]); - var delta = l1 - l0; - var center = centerPoint(touches[0], touches[1]); - _this26._mouseCenter = center; - _this26._zoom += delta; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - var mouse = _this26._mouseCenter; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w, - y: mouse.y * maxOffset / newVideoSize.h - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - touches = curTouches; - evt.preventDefault(); - } else if (curTouches.length > 0) { - var desp = { - x: curTouches[0].x - touches[0].x, - y: curTouches[0].y - touches[0].y - }; - panImage.apply(_assertThisInitialized(_this26), [desp]); - touches = curTouches; - evt.preventDefault(); - } - }); - $(eventCapture).on('touchend', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - if (touches.length > 1) evt.preventDefault(); - }); - - _this26.zoomIn = function () { - if (_this26._zoom >= _this26._maxZoom || !_this26._zoomAvailable) return; - - if (!_this26._mouseCenter) { - _this26._mouseCenter = { - x: $(_this26.domElement).width() / 2, - y: $(_this26.domElement).height() / 2 - }; - } - - _this26._zoom += 25; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - var mouse = _this26._mouseCenter; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w * (maxOffset / 100), - y: mouse.y * maxOffset / newVideoSize.h * (maxOffset / 100) - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - }; - - _this26.zoomOut = function () { - if (_this26._zoom <= 100 || !_this26._zoomAvailable) return; - - if (!_this26._mouseCenter) { - _this26._mouseCenter = { - x: $(_this26.domElement).width() / 2, - y: $(_this26.domElement).height() / 2 - }; - } - - _this26._zoom -= 25; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - var mouse = _this26._mouseCenter; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w * (maxOffset / 100), - y: mouse.y * maxOffset / newVideoSize.h * (maxOffset / 100) - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - }; - - var altScrollMessageContainer = document.createElement('div'); - altScrollMessageContainer.className = "alt-scroll-message-container"; - altScrollMessageContainer.innerHTML = "

            " + paella.utils.dictionary.translate("Use Alt+Scroll to zoom the video") + "

            "; - eventCapture.appendChild(altScrollMessageContainer); - $(altScrollMessageContainer).css({ - opacity: 0.0 - }); - var altScrollMessageTimer = null; - - function clearAltScrollMessage() { - var animate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - animate ? $(altScrollMessageContainer).animate({ - opacity: 0.0 - }) : $(altScrollMessageContainer).css({ - opacity: 0.0 - }); - } - - function showAltScrollMessage() { - if (altScrollMessageTimer) { - clearTimeout(altScrollMessageTimer); - altScrollMessageTimer = null; - } else { - $(altScrollMessageContainer).css({ - opacity: 1.0 - }); - } - - altScrollMessageTimer = setTimeout(function () { - clearAltScrollMessage(); - altScrollMessageTimer = null; - }, 500); - } - - $(eventCapture).on('mousewheel wheel', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - - if (!evt.altKey) { - showAltScrollMessage(); - return; - } else { - clearAltScrollMessage(false); - - if (altScrollMessageTimer) { - clearTimeout(altScrollMessageTimer); - altScrollMessageTimer = null; - } - } - - var mouse = mousePos(evt); - var wheel = wheelDelta(evt); - if (_this26._zoom >= _this26._maxZoom && wheel > 0) return; - _this26._zoom += wheel; - _this26._zoom = _this26._zoom < 100 ? 100 : _this26._zoom; - _this26._zoom = _this26._zoom > _this26._maxZoom ? _this26._maxZoom : _this26._zoom; - var newVideoSize = { - w: $(_this26.domElement).width(), - h: $(_this26.domElement).height() - }; - $(_this26.domElement).css({ - width: _this26._zoom + '%', - height: _this26._zoom + '%' - }); - var maxOffset = _this26._zoom - 100; - var offset = { - x: mouse.x * maxOffset / newVideoSize.w * (maxOffset / 100), - y: mouse.y * maxOffset / newVideoSize.h * (maxOffset / 100) - }; - offset.x = offset.x < maxOffset ? offset.x : maxOffset; - offset.y = offset.y < maxOffset ? offset.y : maxOffset; - $(_this26.domElement).css({ - left: "-" + offset.x + "%", - top: "-" + offset.y + "%" - }); - _this26._zoomOffset = { - x: offset.x, - y: offset.y - }; - paella.events.trigger(paella.events.videoZoomChanged, { - video: _assertThisInitialized(_this26) - }); - _this26._mouseCenter = mouse; - evt.stopPropagation(); - return false; - }); - $(eventCapture).on('mousedown', function (evt) { - _this26._mouseDown = mousePos(evt); - _this26.drag = true; - }); - $(eventCapture).on('mousemove', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - var mouse = mousePos(evt); - var offset = { - x: mouse.x - _this26._mouseDown.x, - y: mouse.y - _this26._mouseDown.y - }; // We have not found out why there are sometimes sudden jumps in the - // position of the mouse cursos, so we avoid the problem - - if ((Math.abs(offset.x) > 80 || Math.abs(_this26.y) > 80) && _this26.drag) { - _this26._mouseDown = mouse; - return; - } - - _this26.drag = evt.buttons > 0; - - if (_this26.drag) { - paella.player.videoContainer.disablePlayOnClick(); - panImage.apply(_assertThisInitialized(_this26), [offset]); - _this26._mouseDown = mouse; - } - }); - $(eventCapture).on('mouseup', function (evt) { - if (!_this26.allowZoom() || !_this26._zoomAvailable) return; - _this26.drag = false; - paella.player.videoContainer.enablePlayOnClick(1000); - }); - $(eventCapture).on('mouseleave', function (evt) { - _this26.drag = false; - }); - } - - return _this26; - } - - _createClass(VideoRect, [{ - key: "canvasData", - get: function get() { - var canvasType = this._stream && Array.isArray(this._stream.canvas) && this._stream.canvas[0]; - - var canvasData = canvasType && paella.getVideoCanvasData(this._stream.canvas[0]) || { - mouseEventsSupport: false, - webglSupport: false - }; - return canvasData; - } - }, { - key: "allowZoom", - value: function allowZoom() { - return !this.canvasData.mouseEventsSupport; - } - }, { - key: "setZoom", - value: function setZoom(zoom, left, top) { - var tween = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; - - if (this.zoomAvailable()) { - this._zoomOffset.x = left; - this._zoomOffset.y = top; - this._zoom = zoom; - - if (tween == 0) { - $(this.domElement).css({ - width: this._zoom + '%', - height: this._zoom + '%', - left: "-" + this._zoomOffset.x + "%", - top: "-" + this._zoomOffset.y + "%" - }); - } else { - $(this.domElement).stop(true, false).animate({ - width: this._zoom + '%', - height: this._zoom + '%', - left: "-" + this._zoomOffset.x + "%", - top: "-" + this._zoomOffset.y + "%" - }, tween, "linear"); - } - - paella.events.trigger(paella.events.videoZoomChanged, { - video: this - }); - } - } - }, { - key: "captureFrame", - value: function captureFrame() { - return Promise.resolve(null); - } - }, { - key: "supportsCaptureFrame", - value: function supportsCaptureFrame() { - return Promise.resolve(false); - } // zoomAvailable will only return true if the zoom is enabled, the - // video plugin supports zoom and the current video resolution is higher than - // the current video size - - }, { - key: "zoomAvailable", - value: function zoomAvailable() { - return this.allowZoom() && this._zoomAvailable; - } - }, { - key: "disableEventCapture", - value: function disableEventCapture() { - this.eventCapture.style.pointerEvents = 'none'; - } - }, { - key: "enableEventCapture", - value: function enableEventCapture() { - this.eventCapture.style.pointerEvents = ''; - } - }]); - - return VideoRect; - }(paella.DomNode); - - paella.VideoRect = VideoRect; - - var VideoElementBase = /*#__PURE__*/function (_paella$VideoRect) { - _inherits(VideoElementBase, _paella$VideoRect); - - var _super11 = _createSuper(VideoElementBase); - - function VideoElementBase(id, stream, containerType, left, top, width, height) { - var _this27; - - _classCallCheck(this, VideoElementBase); - - _this27 = _super11.call(this, id, containerType, left, top, width, height); - _this27._stream = stream; - _this27._ready = false; - _this27._autoplay = false; - _this27._videoQualityStrategy = null; - if (_this27._stream.preview) _this27.setPosterFrame(_this27._stream.preview); - - if (_this27.canvasData.mouseEventsSupport) { - _this27.disableEventCapture(); - } - - return _this27; - } - - _createClass(VideoElementBase, [{ - key: "ready", - get: function get() { - return this._ready; - } - }, { - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "defaultProfile", - value: function defaultProfile() { - return null; - } // Synchronous functions: returns null if the resource is not loaded. Use only if - // the resource is loaded. - - }, { - key: "currentTimeSync", - get: function get() { - return null; - } - }, { - key: "volumeSync", - get: function get() { - return null; - } - }, { - key: "pausedSync", - get: function get() { - return null; - } - }, { - key: "durationSync", - get: function get() { - return null; - } // Initialization functions - - }, { - key: "setVideoQualityStrategy", - value: function setVideoQualityStrategy(strategy) { - this._videoQualityStrategy = strategy; - } - }, { - key: "setPosterFrame", - value: function setPosterFrame(url) { - paella.log.debug("TODO: implement setPosterFrame() function"); - } - }, { - key: "setAutoplay", - value: function setAutoplay(autoplay) { - this._autoplay = autoplay; - } - }, { - key: "setMetadata", - value: function setMetadata(data) { - this._metadata = data; - } - }, { - key: "load", - value: function load() { - return paella_DeferredNotImplemented(); - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return true; - } // Video canvas functions - - }, { - key: "videoCanvas", - value: function videoCanvas() { - return Promise.reject(new Error("VideoElementBase::videoCanvas(): Not implemented in child class.")); - } // Multi audio functions - - }, { - key: "supportsMultiaudio", - value: function supportsMultiaudio() { - return Promise.resolve(false); - } - }, { - key: "getAudioTracks", - value: function getAudioTracks() { - return Promise.resolve([]); - } - }, { - key: "setCurrentAudioTrack", - value: function setCurrentAudioTrack(trackId) { - return Promise.resolve(false); - } - }, { - key: "getCurrentAudioTrack", - value: function getCurrentAudioTrack() { - return Promise.resolve(-1); - } // Playback functions - - }, { - key: "getVideoData", - value: function getVideoData() { - return paella_DeferredNotImplemented(); - } - }, { - key: "play", - value: function play() { - paella.log.debug("TODO: implement play() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "pause", - value: function pause() { - paella.log.debug("TODO: implement pause() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "isPaused", - value: function isPaused() { - paella.log.debug("TODO: implement isPaused() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "duration", - value: function duration() { - paella.log.debug("TODO: implement duration() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - paella.log.debug("TODO: implement setCurrentTime() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "currentTime", - value: function currentTime() { - paella.log.debug("TODO: implement currentTime() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - paella.log.debug("TODO: implement setVolume() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "volume", - value: function volume() { - paella.log.debug("TODO: implement volume() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - paella.log.debug("TODO: implement setPlaybackRate() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "playbackRate", - value: function playbackRate() { - paella.log.debug("TODO: implement playbackRate() function in your VideoElementBase subclass"); - return paella_DeferredNotImplemented(); - } - }, { - key: "getQualities", - value: function getQualities() { - return paella_DeferredNotImplemented(); - } - }, { - key: "setQuality", - value: function setQuality(index) { - return paella_DeferredNotImplemented(); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - return paella_DeferredNotImplemented(); - } - }, { - key: "unload", - value: function unload() { - this._callUnloadEvent(); - - return paella_DeferredNotImplemented(); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredNotImplemented(); // { width:X, height:Y } - } - }, { - key: "goFullScreen", - value: function goFullScreen() { - return paella_DeferredNotImplemented(); - } - }, { - key: "freeze", - value: function freeze() { - return paella_DeferredNotImplemented(); - } - }, { - key: "unFreeze", - value: function unFreeze() { - return paella_DeferredNotImplemented(); - } - }, { - key: "disable", - value: function disable(isMainAudioPlayer) { - console.log("Disable video requested"); - } - }, { - key: "enable", - value: function enable(isMainAudioPlayer) { - console.log("Enable video requested"); - } // Utility functions - - }, { - key: "setClassName", - value: function setClassName(className) { - this.domElement.className = className; - } - }, { - key: "_callReadyEvent", - value: function _callReadyEvent() { - paella.events.trigger(paella.events.singleVideoReady, { - sender: this - }); - } - }, { - key: "_callUnloadEvent", - value: function _callUnloadEvent() { - paella.events.trigger(paella.events.singleVideoUnloaded, { - sender: this - }); - } - }]); - - return VideoElementBase; - }(paella.VideoRect); - - paella.VideoElementBase = VideoElementBase; - - var EmptyVideo = /*#__PURE__*/function (_paella$VideoElementB) { - _inherits(EmptyVideo, _paella$VideoElementB); - - var _super12 = _createSuper(EmptyVideo); - - function EmptyVideo(id, stream, left, top, width, height) { - _classCallCheck(this, EmptyVideo); - - return _super12.call(this, id, stream, 'div', left, top, width, height); - } // Initialization functions - - - _createClass(EmptyVideo, [{ - key: "setPosterFrame", - value: function setPosterFrame(url) {} - }, { - key: "setAutoplay", - value: function setAutoplay(auto) {} - }, { - key: "load", - value: function load() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "play", - value: function play() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "pause", - value: function pause() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "isPaused", - value: function isPaused() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "duration", - value: function duration() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "currentTime", - value: function currentTime() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "volume", - value: function volume() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "playbackRate", - value: function playbackRate() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "unFreeze", - value: function unFreeze() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "freeze", - value: function freeze() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "unload", - value: function unload() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredRejected(new Error("no such compatible video player")); - } - }]); - - return EmptyVideo; - }(paella.VideoElementBase); - - paella.EmptyVideo = EmptyVideo; - - var EmptyVideoFactory = /*#__PURE__*/function (_paella$VideoFactory) { - _inherits(EmptyVideoFactory, _paella$VideoFactory); - - var _super13 = _createSuper(EmptyVideoFactory); - - function EmptyVideoFactory() { - _classCallCheck(this, EmptyVideoFactory); - - return _super13.apply(this, arguments); - } - - _createClass(EmptyVideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - return true; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - return new paella.EmptyVideo(id, streamData, rect.x, rect.y, rect.w, rect.h); - } - }]); - - return EmptyVideoFactory; - }(paella.VideoFactory); - - paella.videoFactories.EmptyVideoFactory = EmptyVideoFactory; - - var Html5Video = /*#__PURE__*/function (_paella$VideoElementB2) { - _inherits(Html5Video, _paella$VideoElementB2); - - var _super14 = _createSuper(Html5Video); - - function Html5Video(id, stream, left, top, width, height, streamName) { - var _this28; - - _classCallCheck(this, Html5Video); - - _this28 = _super14.call(this, id, stream, 'video', left, top, width, height); - _this28._currentQuality = null; - _this28._autoplay = false; - _this28._streamName = streamName || 'mp4'; - _this28._playbackRate = 1; - - if (_this28._stream.sources[_this28._streamName]) { - _this28._stream.sources[_this28._streamName].sort(function (a, b) { - return a.res.h - b.res.h; - }); - } - - _this28.video.preload = "auto"; - - _this28.video.setAttribute("playsinline", ""); //this.video.setAttribute("tabindex","-1"); - - - _this28._configureVideoEvents(_this28.video); - - return _this28; - } - - _createClass(Html5Video, [{ - key: "_configureVideoEvents", - value: function _configureVideoEvents(videoElement) { - var _this29 = this; - - function onProgress(event) { - if (!this._ready && this.video.readyState == 4) { - this._ready = true; - - if (this._initialCurrentTipe !== undefined) { - this.video.currentTime = this._initialCurrentTime; - delete this._initialCurrentTime; - } - - this._callReadyEvent(); - } - } - - var evtCallback = function evtCallback(event) { - onProgress.apply(_this29, [event]); - }; - - $(this.video).bind('progress', evtCallback); - $(this.video).bind('loadstart', evtCallback); - $(this.video).bind('loadedmetadata', evtCallback); - $(this.video).bind('canplay', evtCallback); - $(this.video).bind('oncanplay', evtCallback); // Save current time to resume video - - $(this.video).bind('timeupdate', function (evt) { - _this29._resumeCurrentTime = _this29.video.currentTime; - }); - $(this.video).bind('ended', function (evt) { - paella.events.trigger(paella.events.endVideo); - }); - $(this.video).bind('emptied', function (evt) { - if (_this29._resumeCurrentTime && !isNaN(_this29._resumeCurrentTime)) { - _this29.video.currentTime = _this29._resumeCurrentTime; - } - }); // Fix safari setQuelity bug - - if (paella.utils.userAgent.browser.Safari) { - $(this.video).bind('canplay canplaythrough', function (evt) { - _this29._resumeCurrentTime && (_this29.video.currentTime = _this29._resumeCurrentTime); - }); - } - } - }, { - key: "buffered", - get: function get() { - return this.video && this.video.buffered; - } - }, { - key: "video", - get: function get() { - if (this.domElementType == 'video') { - return this.domElement; - } else { - this._video = this._video || document.createElement('video'); - return this._video; - } - } - }, { - key: "ready", - get: function get() { - // Fix Firefox specific issue when video reaches the end - if (paella.utils.userAgent.browser.Firefox && this.video.currentTime == this.video.duration && this.video.readyState == 2) { - this.video.currentTime = 0; - } - - return this.video.readyState >= 3; - } // Synchronous functions: returns null if the resource is not loaded. Use only if - // the resource is loaded. - - }, { - key: "currentTimeSync", - get: function get() { - return this.ready ? this.video.currentTime : null; - } - }, { - key: "volumeSync", - get: function get() { - return this.ready ? this.video.volume : null; - } - }, { - key: "pausedSync", - get: function get() { - return this.ready ? this.video.paused : null; - } - }, { - key: "durationSync", - get: function get() { - return this.ready ? this.video.duration : null; - } - }, { - key: "_deferredAction", - value: function _deferredAction(action) { - var _this30 = this; - - return new Promise(function (resolve, reject) { - function processResult(actionResult) { - if (actionResult instanceof Promise) { - actionResult.then(function (p) { - return resolve(p); - }).catch(function (err) { - return reject(err); - }); - } else { - resolve(actionResult); - } - } - - if (_this30.ready) { - processResult(action()); - } else { - $(_this30.video).bind('canplay', function () { - processResult(action()); - $(_this30.video).unbind('canplay'); - $(_this30.video).unbind('loadedmetadata'); - }); - } - }); - } - }, { - key: "_getQualityObject", - value: function _getQualityObject(index, s) { - return { - index: index, - res: s.res, - src: s.src, - toString: function toString() { - return this.res.w == 0 ? "auto" : this.res.w + "x" + this.res.h; - }, - shortLabel: function shortLabel() { - return this.res.w == 0 ? "auto" : this.res.h + "p"; - }, - compare: function compare(q2) { - return this.res.w * this.res.h - q2.res.w * q2.res.h; - } - }; - } - }, { - key: "captureFrame", - value: function captureFrame() { - var _this31 = this; - - return new Promise(function (resolve) { - resolve({ - source: _this31.video, - width: _this31.video.videoWidth, - height: _this31.video.videoHeight - }); - }); - } - }, { - key: "supportsCaptureFrame", - value: function supportsCaptureFrame() { - return Promise.resolve(true); - } // Initialization functions - - }, { - key: "getVideoData", - value: function getVideoData() { - var _this32 = this; - - var This = this; - return new Promise(function (resolve, reject) { - _this32._deferredAction(function () { - resolve({ - duration: This.video.duration, - currentTime: This.video.currentTime, - volume: This.video.volume, - paused: This.video.paused, - ended: This.video.ended, - res: { - w: This.video.videoWidth, - h: This.video.videoHeight - } - }); - }); - }); - } - }, { - key: "setPosterFrame", - value: function setPosterFrame(url) { - this._posterFrame = url; - } - }, { - key: "setAutoplay", - value: function setAutoplay(auto) { - this._autoplay = auto; - - if (auto && this.video) { - this.video.setAttribute("autoplay", auto); - } - } - }, { - key: "videoCanvas", - value: function videoCanvas() { - var canvasType = this._stream.canvas || ["video"]; - return paella.getVideoCanvas(canvasType); - } - }, { - key: "webGlDidLoad", - value: function webGlDidLoad() { - return Promise.resolve(); - } - }, { - key: "load", - value: function load() { - var _this33 = this; - - return new Promise(function (resolve, reject) { - var sources = _this33._stream.sources[_this33._streamName]; - - if (_this33._currentQuality === null && _this33._videoQualityStrategy) { - _this33._currentQuality = _this33._videoQualityStrategy.getQualityIndex(sources); - } - - var stream = _this33._currentQuality < sources.length ? sources[_this33._currentQuality] : null; - _this33.video.innerText = ""; - - _this33.videoCanvas().then(function (CanvasClass) { - var canvasInstance = new CanvasClass(stream); - _this33._zoomAvailable = canvasInstance.allowZoom(); - - if (window.$paella_bg && bg.app && canvasInstance instanceof bg.app.WindowController) { - // WebGL canvas - _this33.domElementType = 'canvas'; - - if (stream) { - // WebGL engine load callback - return new Promise(function (webglResolve, webglReject) { - _this33.webGlDidLoad().then(function () { - _this33.canvasController = null; - var mainLoop = bg.app.MainLoop.singleton; - mainLoop.updateMode = bg.app.FrameUpdate.AUTO; - mainLoop.canvas = _this33.domElement; - mainLoop.run(canvasInstance); - return _this33.loadVideoStream(canvasInstance, stream); - }).then(function (canvas) { - webglResolve(canvas); - }).catch(function (err) { - return webglReject(err); - }); - }); - } else { - Promise.reject(new Error("Invalid stream data.")); - } - } else { - return _this33.loadVideoStream(canvasInstance, stream); - } - }).then(function (canvas) { - if (canvas && paella.WebGLCanvas && canvas instanceof paella.WebGLCanvas) { - _this33._video = canvas.video; - - _this33._video.pause(); - - _this33._configureVideoEvents(_this33.video); - } - - resolve(stream); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "loadVideoStream", - value: function loadVideoStream(canvasInstance, stream) { - return canvasInstance.loadVideo(this, stream); - } - }, { - key: "disable", - value: function disable(isMainAudioPlayer) {//if (isMainAudioPlayer) return; - //this._isDisabled = true; - //this._playState = !this.video.paused; - //this.video.pause(); - } - }, { - key: "enable", - value: function enable(isMainAudioPlayer) {//if (isMainAudioPlayer) return; - //this._isDisabled = false; - //if (this._playState) { - // this.video.play(); - //} - } - }, { - key: "getQualities", - value: function getQualities() { - var _this34 = this; - - return new Promise(function (resolve, reject) { - setTimeout(function () { - var result = []; - var sources = _this34._stream.sources[_this34._streamName]; - var index = -1; - sources.forEach(function (s) { - index++; - result.push(_this34._getQualityObject(index, s)); - }); - resolve(result); - }, 10); - }); - } - }, { - key: "setQuality", - value: function setQuality(index) { - var _this35 = this; - - return new Promise(function (resolve) { - var paused = _this35.video.paused; - var sources = _this35._stream.sources[_this35._streamName]; - _this35._currentQuality = index < sources.length ? index : 0; - var currentTime = _this35.video.currentTime; - var This = _this35; - - var onSeek = function onSeek() { - This.unFreeze().then(function () { - resolve(); - This.video.removeEventListener('seeked', onSeek, false); - }); - }; - - _this35.freeze().then(function () { - return _this35.load(); - }).then(function () { - if (!paused) { - _this35.play(); - } - - _this35.video.addEventListener('seeked', onSeek); - - _this35.video.currentTime = currentTime; - }); - }); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - var _this36 = this; - - return new Promise(function (resolve) { - resolve(_this36._getQualityObject(_this36._currentQuality, _this36._stream.sources[_this36._streamName][_this36._currentQuality])); - }); - } - }, { - key: "play", - value: function play() { - var _this37 = this; - - return this._deferredAction(function () { - if (!_this37._isDisabled) { - return _this37.video.play(); - } else { - return Promise.resolve(); - } - }); - } - }, { - key: "pause", - value: function pause() { - var _this38 = this; - - return this._deferredAction(function () { - if (!_this38._isDisabled) { - return _this38.video.pause(); - } else { - return Promise.resolve(); - } - }); - } - }, { - key: "isPaused", - value: function isPaused() { - var _this39 = this; - - return this._deferredAction(function () { - return _this39.video.paused; - }); - } - }, { - key: "duration", - value: function duration() { - var _this40 = this; - - return this._deferredAction(function () { - return _this40.video.duration; - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this41 = this; - - return this._deferredAction(function () { - (time == 0 || time) && !isNaN(time) && (_this41.video.currentTime = time); - }); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this42 = this; - - return this._deferredAction(function () { - return _this42.video.currentTime; - }); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - var _this43 = this; - - return this._deferredAction(function () { - _this43.video.volume = volume; - - if (volume == 0) { - _this43.video.setAttribute("muted", "muted"); - - _this43.video.muted = true; - } else { - _this43.video.removeAttribute("muted"); - - _this43.video.muted = false; - } - }); - } - }, { - key: "volume", - value: function volume() { - var _this44 = this; - - return this._deferredAction(function () { - return _this44.video.volume; - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - var _this45 = this; - - return this._deferredAction(function () { - _this45._playbackRate = rate; - _this45.video.playbackRate = rate; - }); - } - }, { - key: "playbackRate", - value: function playbackRate() { - var _this46 = this; - - return this._deferredAction(function () { - return _this46.video.playbackRate; - }); - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - var macOS10_12_safari = paella.utils.userAgent.system.MacOS && paella.utils.userAgent.system.Version.minor >= 12 && paella.utils.userAgent.browser.Safari; - var iOS = paella.utils.userAgent.system.iOS; // Autoplay does not work from Chrome version 64 - - var chrome_v64 = paella.utils.userAgent.browser.Chrome && paella.utils.userAgent.browser.Version.major == 64; - - if (macOS10_12_safari || iOS || chrome_v64) { - return false; - } else { - return true; - } - } - }, { - key: "goFullScreen", - value: function goFullScreen() { - var _this47 = this; - - return this._deferredAction(function () { - var elem = _this47.video; - - if (elem.requestFullscreen) { - elem.requestFullscreen(); - } else if (elem.msRequestFullscreen) { - elem.msRequestFullscreen(); - } else if (elem.mozRequestFullScreen) { - elem.mozRequestFullScreen(); - } else if (elem.webkitEnterFullscreen) { - elem.webkitEnterFullscreen(); - } - }); - } - }, { - key: "unFreeze", - value: function unFreeze() { - var _this48 = this; - - return this._deferredAction(function () { - var c = document.getElementById(_this48.video.id + "canvas"); - - if (c) { - $(c).remove(); - } - }); - } - }, { - key: "freeze", - value: function freeze() { - var This = this; - return this._deferredAction(function () { - var canvas = document.createElement("canvas"); - canvas.id = This.video.id + "canvas"; - canvas.className = "freezeFrame"; - canvas.width = This.video.videoWidth; - canvas.height = This.video.videoHeight; - canvas.style.cssText = This.video.style.cssText; - canvas.style.zIndex = 2; - var ctx = canvas.getContext("2d"); - ctx.drawImage(This.video, 0, 0, Math.ceil(canvas.width / 16) * 16, Math.ceil(canvas.height / 16) * 16); //Draw image - - This.video.parentElement.appendChild(canvas); - }); - } - }, { - key: "unload", - value: function unload() { - this._callUnloadEvent(); - - return paella_DeferredNotImplemented(); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredNotImplemented(); - } - }]); - - return Html5Video; - }(paella.VideoElementBase); - - paella.Html5Video = Html5Video; - - paella.Html5Video.IsAutoplaySupported = function () { - var debug = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return new Promise(function (resolve) { - // Create video element to test autoplay - var video = document.createElement('video'); - video.src = 'data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAC+htZGF0AAACqQYF//+l3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE1NSByMjkwMSA3ZDBmZjIyIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxOCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTEgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDEgbWU9ZGlhIHN1Ym1lPTEgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MCBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTAgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9MCB0aHJlYWRzPTEgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTEga2V5aW50PTMyMCBrZXlpbnRfbWluPTMyIHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByYz1jcmYgbWJ0cmVlPTAgY3JmPTQwLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IGlwX3JhdGlvPTEuNDAgcGJfcmF0aW89MS4zMCBhcT0xOjEuMDAAgAAAAJBliIQD/2iscx5avG2BdVkxRtUop8zs5zVIqfxQM03W1oVb8spYPP0yjO506xIxgVQ4iSPGOtcDZBVYGqcTatSa730A8XTpnUDpUSrpyaCe/P8eLds/XenOFYMh8UIGMBwzhVOniajqOPFOmmFC20nufGOpJw81hGhgFwCO6a8acwB0P6LNhZZoRD0y2AZMQfEA0AAHAAAACEGaIRiEP5eAANAABwDSGK8UmBURhUGyINeXiuMlXvJnPVVQKigqVGy8PAuVNiWY94iJ/jL/HeT+/usIfmc/dsQ/TV87CTfXhD8C/4xCP3V+DJP8UP3iJdT8okfAuRJF8zkPgh5/J7XzGT8o9pJ+tvlST+g3uwh1330Q9qd4IbnwOQ9dexCHf8mQfVJ57wET8acsIcn6UT6p7yoP2uQ97fFAhrNARXaou2QkEJxrmP6ZBa7TiE6Uqx04OcnChy+OrfwfRWfSYRbS2wmENdDIKUQSkggeXbLb10CIHL5BPgiBydo+HEEPILBbH9zZOdw/77EbN8euVRS/ZcjbZ/D63aLDh1MTme4vfGzFjXkw9r7U8EhcddAmwXGKjo9o53+/8Rnm1rnt6yh3hLD9/htcZnjjGcW9ZQlj6DKIGrrPo/l6C6NyeVr07mB/N6VlGb5fkLBZM42iUNiIGnMJzShmmlFtEsO0mr5CMcFiJdrZQjdIxsYwpU4xlzmD2+oPtjSLVZiDh2lHDRmHubAxXMROEt0z4GkcCYCk832HaXZSM+4vZbUwJa2ysgmfAQMTEM9gxxct7h5xLdrMnHUnB2bXMO2rEnqnnjWHyFYTrzmZTjJ3N4qP+Pv5VHYzZuAa9jnrg35h5hu/Q87uewVnjbJrtcOOm6b9lltPS6n/mkxgxSyqLJVzr/bYt039aTYyhmveJTdeiG7kLfmn9bqjXfxdfZoz53RDcxw+jP7n7TtT8BsB3jUvxe7n5Gbrm9/5QzQ3cxxl9s6ojDMDg3R7Bx//b5rwuSI84z2fuP8/nPxj/wvHNccSL3n77sCEv+AUwlVzHAFkYCkDkdRIORiUg5GJSDkYlIORgKQsjI9E1d0PUP5zV31MSkvI+AAAAAtBmkMYjP/4v5j6wQDGGK/rogCQL/+rZ+PHZ8R11ITSYLDLmXtUdt5a5V+63JHBE/z0/3cCf4av6uOAGtQmr8mCvCxwSI/c7KILm624qm/Kb4fKK5P1GWvX/S84SiSuyTIfk3zVghdRlzZpLZXgddiJjKTGb43OFQCup1nyCbjWgjmOozS6mXGEDsuoVDkSR7/Q8ErEhAZqgHJ5yCxkICvpE+HztDoOSTYiiBCW6shBKQM/Aw5DdbsGWUc/3XEIhH8HXJSDU8mZDApXSSZR+4fbKiOTUHmUgYd7HOLNG544Zy3F+ZPqxMwuGkCo/HxfLXrebdQakkweTwTqUgIDlwvPC181Z5eZ7cDTV905pDXGj/KiRAk3p+hlgHPvRW35PT4b163gUGkmIl0Ds4OBn6G64lkPsnQPNFs8AtwH4PSeYoz9s5uh/jFX0tlr7f+xzN6PuDvyOmKvYhdYK5FLAOkbJ6E/r7fxRZ1g63PPgeLsfir/0iq9K7IW+eWH4ONNCdL5oyV/TSILB+ob8z1ZWUf9p50jIFh6l64geGZ785/8OQanz95/ZPwGF03PMeYdkuH6x5Q/gcx5bg2RejM+RPQ6Vg6D43WOe+1fDKbVqr9P6Y5S9fuwD56fvq62ESHISopAae8/mbMD2la4/h/K9uSYuhxZDNszxgmQmd2kQDoEU6g46KneCXN/b9b5Ez/4iQOfBj4EuXyfp8MlAlFg8P486y4HT9H680pqN9xN164m7ReXPWHU7pw7F9Pw3FEDjQrHHnM3KfE8KWrl2JyxrdR90wr+HPPrkO5v1XT88+iU5MfGOeswl1uQxhiAGn4O62zaMJmDbSrMNY4LEV/jc+TjMQJRwOsUrW8aDyVoo87t8G+Qtfm6fOy6DNK9crM2f3KQJ0YEPc5JM0eSQsjYSFkZFIWRkUgcB1El5HwAAAAIAZ5iRCX/y4AA7liudRsNCYNGAb/ocSIJGilo13xUupVcYzmaVbkEY3nch7y9pfI1qxo3V9n9Q+r84e3e7dCfx+aLdD6S8dDaqzc6eqH9onVdingfJndPc1yaRhn4JD1jsj85o/le4m9cE2W1F8unegGNvOuknfzBmz4/Us9R+kC7xW5e9Z1Z9JsGeb/z6XkKkxiNh1C3Ns5jTVxB9x1poY49zmq+xsXNh0uy75DZf0JM9Uq8ghKrZiQDyAlHf4dqw48mtmlozgUMkh7VJ7vbIW1UNI81pRTT7C3WOOa3mw0RNjAoMLjtm1+VqQBEhHw+6VBvNTwCBkyvjU+kVMA1OU8elyGQX0xTlHRM8iPGg3CO8B5AzpOm2M7J75cG3PPGc42ztXyYzat3TyZ54CyDqZi1/Mn4B6T1fhMSD0uk5lKsOHIktX1Sfud/I3Ew+McUpwm3bxVdAy7uiGeiXWbe3cMBmCruk4yW18G6dEf9prnjcT6HUZG5bBSQGYSQscX2KCZoWxWkVS0w6IkwqdVJ+Akyey/Hl0MyrcAMI6Sgq3HMn95sBcc4ZadQLT31gNKo6qyebwmyK63HlMTK40Zj3FGuboBQ3Zsg87Jf3Gg1SDlG6fRVl2+5Cc6q+0OcUNRyCfLIG157ZHTSCwD9UpZtZDLki0BCLgAAAAhBmmQYiv+BgQDyne7dSHRhSQ/D31OEhh0h14FMQDwlvgJODIIYGxb7iHQo1mvJn3hOUUli9mTrUMuuPv/W2bsX3X7l9k7jtvT/Cuf4Kmbbhn0zmtjx7GWFyjrJfyHHxs5mxuTjdr2/drXoPhh1rb2XOnE9H3BdBqm1I+K5Sd1hYCevn6PbJcDyUHpysOZeLu+VoYklOlicG52cbxZbzvVeiS4jb+qyJoL62Ox+nSrUhOkCNMf8dz5iEi+C5iYZciyXk6gmIvSJVQDNTiO2i1a6pGORhiNVWGAMBHNHyHbmWtqB9AYbSdGR5qQzHnGF9HWaHfTzIqQMNEioRwE00KEllO+UcuPFmOs0Kl9lgy1DgKSKfGaaVFc7RNrn0nOddM6OfOG51GuoJSCnOpRjIvLAMAAAAA1NfU1+Ro9v/o+AANDABwAABedtb292AAAAbG12aGQAAAAA18kDNdfJAzUAAAPoAAAAowABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAGGlvZHMAAAAAEICAgAcAT////v7/AAACknRyYWsAAABcdGtoZAAAAAPXyQM118kDNQAAAAEAAAAAAAAAnwAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAOAAAACAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAJ8AABZEAAEAAAAAAgptZGlhAAAAIG1kaGQAAAAA18kDNdfJAzUAAV+QAAA3qlXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAG1bWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAABdXN0YmwAAACYc3RzZAAAAAAAAAABAAAAiGF2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAOAAgAEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAyYXZjQwFNQAr/4QAaZ01ACuyiLy+AtQYBBkAAAATAAAEsI8SJZYABAAVo74OcgAAAABhzdHRzAAAAAAAAAAEAAAAFAAALIgAAABRzdHNzAAAAAAAAAAEAAAABAAAAEXNkdHAAAAAAIBAQGBAAAAAwY3R0cwAAAAAAAAAEAAAAAgAAFkQAAAABAAAhZgAAAAEAAAsiAAAAAQAAFkQAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAKHN0c3oAAAAAAAAAAAAAAAUAAANBAAAADAAAAA8AAAAMAAAADAAAACRzdGNvAAAAAAAAAAUAAAAwAAADdQAABhAAAAjPAAAKyQAAAlp0cmFrAAAAXHRraGQAAAAD18kDNdfJAzUAAAACAAAAAAAAAKMAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAABzAAAIQAABAAAAAAG+bWRpYQAAACBtZGhkAAAAANfJAzXXyQM1AACsRAAAHABVxAAAAAAAJWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABNb25vAAAAAXFtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAATVzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAAAAAAAAAABYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAAHAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAwc3RzegAAAAAAAAAAAAAABwAAAAQAAAAEAAACiwAAArAAAAHuAAABNwAAAAQAAAAsc3RjbwAAAAAAAAAHAAADcQAAA4EAAAOFAAAGHwAACNsAAArVAAAMDAAAABpzZ3BkAQAAAHJvbGwAAAACAAAAAf//AAAAHHNiZ3AAAAAAcm9sbAAAAAEAAAAHAAAAAQAAABR1ZHRhAAAADG5hbWVNb25vAAAAb3VkdGEAAABnbWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAA6aWxzdAAAADKpdG9vAAAAKmRhdGEAAAABAAAAAEhhbmRCcmFrZSAxLjEuMiAyMDE4MDkwNTAw'; - video.load(); //video.style.display = 'none'; - - if (debug) { - video.style = "position: fixed; top: 0px; right: 0px; z-index: 1000000;"; - document.body.appendChild(video); - } else { - video.style.display = 'none'; - } - - video.playing = false; - video.play().then(function (status) { - resolve(true); - }).catch(function (err) { - resolve(false); - }); - }); - }; - - var Html5VideoFactory = /*#__PURE__*/function () { - function Html5VideoFactory() { - _classCallCheck(this, Html5VideoFactory); - } - - _createClass(Html5VideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - try { - if (paella.videoFactories.Html5VideoFactory.s_instances > 0 && paella.utils.userAgent.system.iOS && paella.utils.userAgent.system.Version.major <= 10 && paella.utils.userAgent.system.Version.minor < 3) { - return false; - } - - for (var key in streamData.sources) { - if (key == 'mp4' || key == 'mp3') return true; - } - } catch (e) {} - - return false; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - ++paella.videoFactories.Html5VideoFactory.s_instances; - return new paella.Html5Video(id, streamData, rect.x, rect.y, rect.w, rect.h); - } - }]); - - return Html5VideoFactory; - }(); - - paella.videoFactories.Html5VideoFactory = Html5VideoFactory; - paella.videoFactories.Html5VideoFactory.s_instances = 0; - - var ImageVideo = /*#__PURE__*/function (_paella$VideoElementB3) { - _inherits(ImageVideo, _paella$VideoElementB3); - - var _super15 = _createSuper(ImageVideo); - - function ImageVideo(id, stream, left, top, width, height) { - var _this49; - - _classCallCheck(this, ImageVideo); - - _this49 = _super15.call(this, id, stream, 'img', left, top, width, height); - _this49._posterFrame = null; - _this49._currentQuality = null; - _this49._currentTime = 0; - _this49._duration = 0; - _this49._ended = false; - _this49._playTimer = null; - _this49._playbackRate = 1; - _this49._frameArray = null; - - _this49._stream.sources.image.sort(function (a, b) { - return a.res.h - b.res.h; - }); - - return _this49; - } - - _createClass(ImageVideo, [{ - key: "img", - get: function get() { - return this.domElement; - } - }, { - key: "imgStream", - get: function get() { - this._stream.sources.image[this._currentQuality]; - } - }, { - key: "_paused", - get: function get() { - return this._playTimer == null; - } - }, { - key: "_deferredAction", - value: function _deferredAction(action) { - var _this50 = this; - - return new Promise(function (_resolve) { - if (_this50.ready) { - _resolve(action()); - } else { - var _resolve = function resolve() { - _this50._ready = true; - - _resolve(action()); - }; - - $(_this50.video).bind('paella:imagevideoready', _resolve); - } - }); - } - }, { - key: "_getQualityObject", - value: function _getQualityObject(index, s) { - return { - index: index, - res: s.res, - src: s.src, - toString: function toString() { - return Number(this.res.w) + "x" + Number(this.res.h); - }, - shortLabel: function shortLabel() { - return this.res.h + "p"; - }, - compare: function compare(q2) { - return Number(this.res.w) * Number(this.res.h) - Number(q2.res.w) * Number(q2.res.h); - } - }; - } - }, { - key: "_loadCurrentFrame", - value: function _loadCurrentFrame() { - var This = this; - - if (this._frameArray) { - var frame = this._frameArray[0]; - - this._frameArray.some(function (f) { - if (This._currentTime < f.time) { - return true; - } else { - frame = f.src; - } - }); - - this.img.src = frame; - } - } // Initialization functions - - /*allowZoom:function() { - return false; - },*/ - - }, { - key: "getVideoData", - value: function getVideoData() { - var _this51 = this; - - return new Promise(function (resolve) { - _this51._deferredAction(function () { - var imgStream = _this51._stream.sources.image[_this51._currentQuality]; - var videoData = { - duration: _this51._duration, - currentTime: _this51._currentTime, - volume: 0, - paused: _this51._paused, - ended: _this51._ended, - res: { - w: imgStream.res.w, - h: imgStream.res.h - } - }; - resolve(videoData); - }); - }); - } - }, { - key: "setPosterFrame", - value: function setPosterFrame(url) { - this._posterFrame = url; - } - }, { - key: "setAutoplay", - value: function setAutoplay(auto) { - this._autoplay = auto; - - if (auto && this.video) { - this.video.setAttribute("autoplay", auto); - } - } - }, { - key: "load", - value: function load() { - var This = this; - var sources = this._stream.sources.image; - - if (this._currentQuality === null && this._videoQualityStrategy) { - this._currentQuality = this._videoQualityStrategy.getQualityIndex(sources); - } - - var stream = this._currentQuality < sources.length ? sources[this._currentQuality] : null; - - if (stream) { - this._frameArray = []; - - for (var key in stream.frames) { - var time = Math.floor(Number(key.replace("frame_", ""))); - - this._frameArray.push({ - src: stream.frames[key], - time: time - }); - } - - this._frameArray.sort(function (a, b) { - return a.time - b.time; - }); - - this._ready = true; - this._currentTime = 0; - this._duration = stream.duration; - - this._loadCurrentFrame(); - - paella.events.trigger("paella:imagevideoready"); - return this._deferredAction(function () { - return stream; - }); - } else { - return paella_DeferredRejected(new Error("Could not load video: invalid quality stream index")); - } - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return true; - } - }, { - key: "getQualities", - value: function getQualities() { - var _this52 = this; - - return new Promise(function (resolve) { - setTimeout(function () { - var result = []; - var sources = _this52._stream.sources[_this52._streamName]; - var index = -1; - sources.forEach(function (s) { - index++; - result.push(_this52._getQualityObject(index, s)); - }); - resolve(result); - }, 10); - }); - } - }, { - key: "setQuality", - value: function setQuality(index) { - var _this53 = this; - - return new Promise(function (resolve) { - var paused = _this53._paused; - var sources = _this53._stream.sources.image; - _this53._currentQuality = index < sources.length ? index : 0; - var currentTime = _this53._currentTime; - - _this53.load().then(function () { - this._loadCurrentFrame(); - - resolve(); - }); - }); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - var _this54 = this; - - return new Promise(function (resolve) { - resolve(_this54._getQualityObject(_this54._currentQuality, _this54._stream.sources.image[_this54._currentQuality])); - }); - } - }, { - key: "play", - value: function play() { - var This = this; - return this._deferredAction(function () { - This._playTimer = new paella.utils.Timer(function () { - This._currentTime += 0.25 * This._playbackRate; - - This._loadCurrentFrame(); - }, 250); - This._playTimer.repeat = true; - }); - } - }, { - key: "pause", - value: function pause() { - var This = this; - return this._deferredAction(function () { - This._playTimer.repeat = false; - This._playTimer = null; - }); - } - }, { - key: "isPaused", - value: function isPaused() { - var _this55 = this; - - return this._deferredAction(function () { - return _this55._paused; - }); - } - }, { - key: "duration", - value: function duration() { - var _this56 = this; - - return this._deferredAction(function () { - return _this56._duration; - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this57 = this; - - return this._deferredAction(function () { - _this57._currentTime = time; - - _this57._loadCurrentFrame(); - }); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this58 = this; - - return this._deferredAction(function () { - return _this58._currentTime; - }); - } - }, { - key: "setVolume", - value: function setVolume(volume) { - return this._deferredAction(function () {// No audo sources in image video - }); - } - }, { - key: "volume", - value: function volume() { - return this._deferredAction(function () { - // No audo sources in image video - return 0; - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - var _this59 = this; - - return this._deferredAction(function () { - _this59._playbackRate = rate; - }); - } - }, { - key: "playbackRate", - value: function playbackRate() { - var _this60 = this; - - return this._deferredAction(function () { - return _this60._playbackRate; - }); - } - }, { - key: "goFullScreen", - value: function goFullScreen() { - var _this61 = this; - - return this._deferredAction(function () { - var elem = _this61.img; - - if (elem.requestFullscreen) { - elem.requestFullscreen(); - } else if (elem.msRequestFullscreen) { - elem.msRequestFullscreen(); - } else if (elem.mozRequestFullScreen) { - elem.mozRequestFullScreen(); - } else if (elem.webkitEnterFullscreen) { - elem.webkitEnterFullscreen(); - } - }); - } - }, { - key: "unFreeze", - value: function unFreeze() { - return this._deferredAction(function () {}); - } - }, { - key: "freeze", - value: function freeze() { - return this._deferredAction(function () {}); - } - }, { - key: "unload", - value: function unload() { - this._callUnloadEvent(); - - return paella_DeferredNotImplemented(); - } - }, { - key: "getDimensions", - value: function getDimensions() { - return paella_DeferredNotImplemented(); - } - }]); - - return ImageVideo; - }(paella.VideoElementBase); - - paella.ImageVideo = ImageVideo; - - var ImageVideoFactory = /*#__PURE__*/function () { - function ImageVideoFactory() { - _classCallCheck(this, ImageVideoFactory); - } - - _createClass(ImageVideoFactory, [{ - key: "isStreamCompatible", - value: function isStreamCompatible(streamData) { - try { - for (var key in streamData.sources) { - if (key == 'image') return true; - } - } catch (e) {} - - return false; - } - }, { - key: "getVideoObject", - value: function getVideoObject(id, streamData, rect) { - return new paella.ImageVideo(id, streamData, rect.x, rect.y, rect.w, rect.h); - } - }]); - - return ImageVideoFactory; - }(); - - paella.videoFactories.ImageVideoFactory = ImageVideoFactory; -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community 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.osedu.org/licenses/ECL-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. -*/ - - -(function () { - var BackgroundContainer = /*#__PURE__*/function (_paella$DomNode4) { - _inherits(BackgroundContainer, _paella$DomNode4); - - var _super16 = _createSuper(BackgroundContainer); - - function BackgroundContainer(id, image) { - var _this62; - - _classCallCheck(this, BackgroundContainer); - - _this62 = _super16.call(this, 'img', id, { - position: 'relative', - top: '0px', - left: '0px', - right: '0px', - bottom: '0px', - zIndex: GlobalParams.background.zIndex - }); - - _this62.domElement.setAttribute('src', image); - - _this62.domElement.setAttribute('alt', ''); - - _this62.domElement.setAttribute('width', '100%'); - - _this62.domElement.setAttribute('height', '100%'); - - return _this62; - } - - _createClass(BackgroundContainer, [{ - key: "setImage", - value: function setImage(image) { - this.domElement.setAttribute('src', image); - } - }]); - - return BackgroundContainer; - }(paella.DomNode); - - paella.BackgroundContainer = BackgroundContainer; - - var VideoOverlay = /*#__PURE__*/function (_paella$DomNode5) { - _inherits(VideoOverlay, _paella$DomNode5); - - var _super17 = _createSuper(VideoOverlay); - - function VideoOverlay() { - var _this63; - - _classCallCheck(this, VideoOverlay); - - var style = { - position: 'absolute', - left: '0px', - right: '0px', - top: '0px', - bottom: '0px', - overflow: 'hidden', - zIndex: 10 - }; - _this63 = _super17.call(this, 'div', 'overlayContainer', style); - - _this63.domElement.setAttribute("role", "main"); - - return _this63; - } - - _createClass(VideoOverlay, [{ - key: "size", - get: function get() { - if (!this._size) { - this._size = { - w: 1280, - h: 720 - }; - } - - return this._size; - } - }, { - key: "_generateId", - value: function _generateId() { - return Math.ceil(Date.now() * Math.random()); - } - }, { - key: "enableBackgroundMode", - value: function enableBackgroundMode() { - this.domElement.className = 'overlayContainer background'; - } - }, { - key: "disableBackgroundMode", - value: function disableBackgroundMode() { - this.domElement.className = 'overlayContainer'; - } - }, { - key: "clear", - value: function clear() { - this.domElement.innerText = ""; - } - }, { - key: "getVideoRect", - value: function getVideoRect(index) { - return paella.player.videoContainer.getVideoRect(index); - } - }, { - key: "addText", - value: function addText(text, rect, isDebug) { - var textElem = document.createElement('div'); - textElem.innerText = text; - textElem.className = "videoOverlayText"; - if (isDebug) textElem.style.backgroundColor = "red"; - return this.addElement(textElem, rect); - } - }, { - key: "addElement", - value: function addElement(element, rect) { - this.domElement.appendChild(element); - element.style.position = 'absolute'; - element.style.left = this.getHSize(rect.left) + '%'; - element.style.top = this.getVSize(rect.top) + '%'; - element.style.width = this.getHSize(rect.width) + '%'; - element.style.height = this.getVSize(rect.height) + '%'; - return element; - } - }, { - key: "getLayer", - value: function getLayer(id, zindex) { - id = id || this._generateId(); - return $(this.domElement).find("#" + id)[0] || this.addLayer(id, zindex); - } - }, { - key: "addLayer", - value: function addLayer(id, zindex) { - zindex = zindex || 10; - var element = document.createElement('div'); - element.className = "row"; - element.id = id || this._generateId(); - return this.addElement(element, { - left: 0, - top: 0, - width: 1280, - height: 720 - }); - } - }, { - key: "removeLayer", - value: function removeLayer(id) { - var elem = $(this.domElement).find("#" + id)[0]; - - if (elem) { - this.domElement.removeChild(elem); - } - } - }, { - key: "removeElement", - value: function removeElement(element) { - if (element) { - try { - this.domElement.removeChild(element); - } catch (e) {} - } - } - }, { - key: "getVSize", - value: function getVSize(px) { - return px * 100 / this.size.h; - } - }, { - key: "getHSize", - value: function getHSize(px) { - return px * 100 / this.size.w; - } - }]); - - return VideoOverlay; - }(paella.DomNode); - - paella.VideoOverlay = VideoOverlay; - - var VideoWrapper = /*#__PURE__*/function (_paella$DomNode6) { - _inherits(VideoWrapper, _paella$DomNode6); - - var _super18 = _createSuper(VideoWrapper); - - function VideoWrapper(id, left, top, width, height) { - var _this64; - - _classCallCheck(this, VideoWrapper); - - var relativeSize = new paella.RelativeVideoSize(); - var percentTop = relativeSize.percentVSize(top) + '%'; - var percentLeft = relativeSize.percentWSize(left) + '%'; - var percentWidth = relativeSize.percentWSize(width) + '%'; - var percentHeight = relativeSize.percentVSize(height) + '%'; - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute', - zIndex: GlobalParams.video.zIndex, - overflow: 'hidden' - }; - _this64 = _super18.call(this, 'div', id, style); - _this64._rect = { - left: left, - top: top, - width: width, - height: height - }; - _this64.domElement.className = "videoWrapper"; - return _this64; - } - - _createClass(VideoWrapper, [{ - key: "setRect", - value: function setRect(rect, animate) { - this._rect = JSON.parse(JSON.stringify(rect)); - var relativeSize = new paella.RelativeVideoSize(); - var percentTop = relativeSize.percentVSize(rect.top) + '%'; - var percentLeft = relativeSize.percentWSize(rect.left) + '%'; - var percentWidth = relativeSize.percentWSize(rect.width) + '%'; - var percentHeight = relativeSize.percentVSize(rect.height) + '%'; - var style = { - top: percentTop, - left: percentLeft, - width: percentWidth, - height: percentHeight, - position: 'absolute' - }; - - if (animate) { - this.disableClassName(); - var thisClass = this; - $(this.domElement).animate(style, 400, function () { - thisClass.enableClassName(); - paella.events.trigger(paella.events.setComposition, { - video: thisClass - }); - }); - this.enableClassNameAfter(400); - } else { - $(this.domElement).css(style); - paella.events.trigger(paella.events.setComposition, { - video: this - }); - } - } - }, { - key: "getRect", - value: function getRect() { - return this._rect; - } - }, { - key: "disableClassName", - value: function disableClassName() { - this.classNameBackup = this.domElement.className; - this.domElement.className = ""; - } - }, { - key: "enableClassName", - value: function enableClassName() { - this.domElement.className = this.classNameBackup; - } - }, { - key: "enableClassNameAfter", - value: function enableClassNameAfter(millis) { - setTimeout("$('#" + this.domElement.id + "')[0].className = '" + this.classNameBackup + "'", millis); - } - }, { - key: "setVisible", - value: function setVisible(visible, animate) { - var _this65 = this; - - if (typeof visible == "string") { - visible = /true/i.test(visible) ? true : false; - } - - if (visible && animate) { - $(this.domElement).show(); - $(this.domElement).animate({ - opacity: 1.0 - }, 300); - } else if (visible && !animate) { - $(this.domElement).show(); - } else if (!visible && animate) { - $(this.domElement).animate({ - opacity: 0.0 - }, 300, function () { - return $(_this65.domElement).hide(); - }); - } else if (!visible && !animate) { - $(this.domElement).hide(); - } - } - }, { - key: "setLayer", - value: function setLayer(layer) { - this.domElement.style.zIndex = layer; - } - }]); - - return VideoWrapper; - }(paella.DomNode); - - paella.VideoWrapper = VideoWrapper; - paella.SeekType = { - FULL: 1, - BACKWARDS_ONLY: 2, - FORWARD_ONLY: 3, - DISABLED: 4 - }; // This function is used to manage the timer to enable and disable the click and double click events - // interaction with the video container timeout. - - function clearClickEventsTimeout() { - if (this._clickEventsTimeout) { - clearTimeout(this._clickEventsTimeout); - this._clickEventsTimeout = null; - } - } - - var VideoContainerBase = /*#__PURE__*/function (_paella$DomNode7) { - _inherits(VideoContainerBase, _paella$DomNode7); - - var _super19 = _createSuper(VideoContainerBase); - - function VideoContainerBase(id) { - var _this66; - - _classCallCheck(this, VideoContainerBase); - - var style = { - position: 'absolute', - left: '0px', - right: '0px', - top: '0px', - bottom: '0px', - overflow: 'hidden' - }; - _this66 = _super19.call(this, 'div', id, style); - _this66._trimming = { - enabled: false, - start: 0, - end: 0 - }; - _this66.timeupdateEventTimer = null; - _this66.timeupdateInterval = 250; - _this66.masterVideoData = null; - _this66.slaveVideoData = null; - _this66.currentMasterVideoData = null; - _this66.currentSlaveVideoData = null; - _this66._force = false; - _this66._clickEventsEnabled = true; - _this66._seekDisabled = false; - _this66._seekType = paella.SeekType.FULL; - _this66._seekTimeLimit = 0; - _this66._attenuationEnabled = false; - $(_this66.domElement).dblclick(function (evt) { - if (_this66._clickEventsEnabled) { - paella.player.isFullScreen() ? paella.player.exitFullScreen() : paella.player.goFullScreen(); - } - }); - var dblClickTimer = null; - $(_this66.domElement).click(function (evt) { - var doClick = function doClick() { - if (!_this66._clickEventsEnabled) return; - paella.player.videoContainer.paused().then(function (paused) { - // If some player needs mouse events support, the click is ignored - if (_this66.streamProvider.videoPlayers.some(function (p) { - return p.canvasData.mouseEventsSupport; - })) { - return; - } - - if (paused) { - paella.player.play(); - } else { - paella.player.pause(); - } - }); - }; // the dblClick timer prevents the single click from running when the user double clicks - - - if (dblClickTimer) { - clearTimeout(dblClickTimer); - dblClickTimer = null; - } else { - dblClickTimer = setTimeout(function () { - dblClickTimer = null; - doClick(); - }, 200); - } - }); - - _this66.domElement.addEventListener("touchstart", function (event) { - if (paella.player.controls) { - paella.player.controls.restartHideTimer(); - } - }); - - return _this66; - } - - _createClass(VideoContainerBase, [{ - key: "attenuationEnabled", - get: function get() { - return this._attenuationEnabled; - }, - set: function set(att) { - this._attenuationEnabled = att; - Array.from(paella.player.videoContainer.container.domElement.children).forEach(function (ch) { - if (ch.id == "overlayContainer") { - return; - } - - if (att) { - $(ch).addClass("dimmed-element"); - } else { - $(ch).removeClass("dimmed-element"); - } - }); - } - }, { - key: "seekType", - get: function get() { - return this._seekType; - }, - set: function set(type) { - switch (type) { - case paella.SeekType.FULL: - case paella.SeekType.BACKWARDS_ONLY: - case paella.SeekType.FORWARD_ONLY: - case paella.SeekType.DISABLED: - this._seekType = type; - paella.events.trigger(paella.events.seekAvailabilityChanged, { - type: type, - enabled: type == paella.SeekType.FULL, - disabled: type != paella.SeekType.FULL - }); - break; - - default: - throw new Error("Invalid seekType. Allowed seek types:\n\t\t\t\tpaella.SeekType.FULL\n\t\t\t\tpaella.SeekType.BACKWARDS_ONLY\n\t\t\t\tpaella.SeekType.FORWARD_ONLY\n\t\t\t\tpaella.SeekType.DISABLED"); - } - } - }, { - key: "triggerTimeupdate", - value: function triggerTimeupdate() { - var _this67 = this; - - var paused = 0; - var duration = 0; - this.paused().then(function (p) { - paused = p; - return _this67.duration(); - }).then(function (d) { - duration = d; - return _this67.currentTime(); - }).then(function (currentTime) { - if (!paused || _this67._force) { - _this67._seekTimeLimit = currentTime > _this67._seekTimeLimit ? currentTime : _this67._seekTimeLimit; - _this67._force = false; - paella.events.trigger(paella.events.timeupdate, { - videoContainer: _this67, - currentTime: currentTime, - duration: duration - }); - } - }); - } - }, { - key: "startTimeupdate", - value: function startTimeupdate() { - var _this68 = this; - - this.timeupdateEventTimer = new paella.utils.Timer(function (timer) { - _this68.triggerTimeupdate(); - }, this.timeupdateInterval); - this.timeupdateEventTimer.repeat = true; - } - }, { - key: "stopTimeupdate", - value: function stopTimeupdate() { - if (this.timeupdateEventTimer) { - this.timeupdateEventTimer.repeat = false; - } - - this.timeupdateEventTimer = null; - } - }, { - key: "enablePlayOnClick", - value: function enablePlayOnClick() { - var _this69 = this; - - var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - clearClickEventsTimeout.apply(this); - - if (timeout) { - this._clickEventsTimeout = setTimeout(function () { - _this69._clickEventsEnabled = true; - }, timeout); - } else { - this._clickEventsEnabled = true; - } - } - }, { - key: "disablePlayOnClick", - value: function disablePlayOnClick() { - clearClickEventsTimeout.apply(this); - this._clickEventsEnabled = false; - } - }, { - key: "isPlayOnClickEnabled", - value: function isPlayOnClickEnabled() { - return this._clickEventsEnabled; - } - }, { - key: "play", - value: function play() { - this.streamProvider.startVideoSync(this.audioPlayer); - this.startTimeupdate(); - setTimeout(function () { - return paella.events.trigger(paella.events.play); - }, 50); - } - }, { - key: "pause", - value: function pause() { - paella.events.trigger(paella.events.pause); - this.stopTimeupdate(); - this.streamProvider.stopVideoSync(); - } - }, { - key: "seekTo", - value: function seekTo(newPositionPercent) { - var _this70 = this; - - return new Promise(function (resolve, reject) { - var time = 0; - paella.player.videoContainer.currentTime().then(function (t) { - time = t; - return paella.player.videoContainer.duration(); - }).then(function (duration) { - if (_this70._seekTimeLimit > 0 && _this70._seekType == paella.SeekType.BACKWARDS_ONLY) { - time = _this70._seekTimeLimit; - } - - var currentPercent = time / duration * 100; - - switch (_this70._seekType) { - case paella.SeekType.FULL: - break; - - case paella.SeekType.BACKWARDS_ONLY: - if (newPositionPercent > currentPercent) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.FORWARD_ONLY: - if (newPositionPercent < currentPercent) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.DISABLED: - reject(new Error("Warning: Seek is disabled")); - return; - } - - _this70.setCurrentPercent(newPositionPercent).then(function (timeData) { - _this70._force = true; - - _this70.triggerTimeupdate(); - - paella.events.trigger(paella.events.seekToTime, { - newPosition: timeData.time - }); - paella.events.trigger(paella.events.seekTo, { - newPositionPercent: newPositionPercent - }); - resolve(); - }); - }); - }); - } - }, { - key: "seekToTime", - value: function seekToTime(time) { - var _this71 = this; - - return new Promise(function (resolve, reject) { - paella.player.videoContainer.currentTime().then(function (currentTime) { - if (_this71._seekTimeLimit && _this71._seekType == paella.SeekType.BACKWARDS_ONLY) { - currentTime = _this71._seekTimeLimit; - } - - switch (_this71._seekType) { - case paella.SeekType.FULL: - break; - - case paella.SeekType.BACKWARDS_ONLY: - if (time > currentTime) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.FORWARD_ONLY: - if (time < currentTime) { - reject(new Error("Warning: Seek is disabled")); - return; - } - - break; - - case paella.SeekType.DISABLED: - reject(new Error("Warning: Seek is disabled")); - return; - } - - _this71.setCurrentTime(time).then(function (timeData) { - _this71._force = true; - - _this71.triggerTimeupdate(); - - var percent = timeData.time * 100 / timeData.duration; - paella.events.trigger(paella.events.seekToTime, { - newPosition: timeData.time - }); - paella.events.trigger(paella.events.seekTo, { - newPositionPercent: percent - }); - }); - }); - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(params) { - paella.events.trigger(paella.events.setPlaybackRate, { - rate: params - }); - } - }, { - key: "mute", - value: function mute() {} - }, { - key: "unmute", - value: function unmute() {} - }, { - key: "setVolume", - value: function setVolume(params) {} - }, { - key: "volume", - value: function volume() { - return 1; - } - }, { - key: "trimStart", - value: function trimStart() { - var _this72 = this; - - return new Promise(function (resolve) { - resolve(_this72._trimming.start); - }); - } - }, { - key: "trimEnd", - value: function trimEnd() { - var _this73 = this; - - return new Promise(function (resolve) { - resolve(_this73._trimming.end); - }); - } - }, { - key: "trimEnabled", - value: function trimEnabled() { - var _this74 = this; - - return new Promise(function (resolve) { - resolve(_this74._trimming.enabled); - }); - } - }, { - key: "trimming", - value: function trimming() { - var _this75 = this; - - return new Promise(function (resolve) { - resolve(_this75._trimming); - }); - } - }, { - key: "enableTrimming", - value: function enableTrimming() { - this._trimming.enabled = true; - var cap = paella.captions.getActiveCaptions(); - if (cap !== undefined) paella.plugins.captionsPlugin.buildBodyContent(cap._captions, "list"); - paella.events.trigger(paella.events.setTrim, { - trimEnabled: this._trimming.enabled, - trimStart: this._trimming.start, - trimEnd: this._trimming.end - }); - } - }, { - key: "disableTrimming", - value: function disableTrimming() { - this._trimming.enabled = false; - var cap = paella.captions.getActiveCaptions(); - if (cap !== undefined) paella.plugins.captionsPlugin.buildBodyContent(cap._captions, "list"); - paella.events.trigger(paella.events.setTrim, { - trimEnabled: this._trimming.enabled, - trimStart: this._trimming.start, - trimEnd: this._trimming.end - }); - } - }, { - key: "setTrimming", - value: function setTrimming(start, end) { - var _this76 = this; - - return new Promise(function (resolve) { - var currentTime = 0; - - _this76.currentTime(true).then(function (c) { - currentTime = c; - return _this76.duration(); - }).then(function (duration) { - _this76._trimming.start = Math.floor(start); - _this76._trimming.end = Math.floor(end); - - if (_this76._trimming.enabled) { - if (currentTime < _this76._trimming.start) { - _this76.setCurrentTime(0); - } - - if (currentTime > _this76._trimming.end) { - _this76.setCurrentTime(duration); - } - - var cap = paella.captions.getActiveCaptions(); - if (cap !== undefined) paella.plugins.captionsPlugin.buildBodyContent(cap._captions, "list"); - } - - paella.events.trigger(paella.events.setTrim, { - trimEnabled: _this76._trimming.enabled, - trimStart: _this76._trimming.start, - trimEnd: _this76._trimming.end - }); - resolve(); - }); - }); - } - }, { - key: "setTrimmingStart", - value: function setTrimmingStart(start) { - return this.setTrimming(start, this._trimming.end); - } - }, { - key: "setTrimmingEnd", - value: function setTrimmingEnd(end) { - return this.setTrimming(this._trimming.start, end); - } - }, { - key: "setCurrentPercent", - value: function setCurrentPercent(percent) { - var _this77 = this; - - var duration = 0; - return new Promise(function (resolve) { - _this77.duration().then(function (d) { - duration = d; - return _this77.trimming(); - }).then(function (trimming) { - var position = 0; - - if (trimming.enabled) { - var start = trimming.start; - var end = trimming.end; - duration = end - start; - var trimedPosition = percent * duration / 100; - position = parseFloat(trimedPosition); - } else { - position = percent * duration / 100; - } - - return _this77.setCurrentTime(position); - }).then(function (timeData) { - resolve(timeData); - }); - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - paella.log.debug("VideoContainerBase.setCurrentTime(" + time + ")"); - } - }, { - key: "currentTime", - value: function currentTime() { - paella.log.debug("VideoContainerBase.currentTime()"); - return 0; - } - }, { - key: "duration", - value: function duration() { - paella.log.debug("VideoContainerBase.duration()"); - return 0; - } - }, { - key: "paused", - value: function paused() { - paella.log.debug("VideoContainerBase.paused()"); - return true; - } - }, { - key: "setupVideo", - value: function setupVideo(onSuccess) { - paella.log.debug("VideoContainerBase.setupVide()"); - } - }, { - key: "isReady", - value: function isReady() { - paella.log.debug("VideoContainerBase.isReady()"); - return true; - } - }, { - key: "onresize", - value: function (_onresize) { - function onresize() { - return _onresize.apply(this, arguments); - } - - onresize.toString = function () { - return _onresize.toString(); - }; - - return onresize; - }(function () { - _get(_getPrototypeOf(VideoContainerBase.prototype), "onresize", this).call(this, onresize); - }) - }, { - key: "ended", - value: function ended() { - var _this78 = this; - - return new Promise(function (resolve) { - var duration = 0; - - _this78.duration().then(function (d) { - duration = d; - return _this78.currentTime(); - }).then(function (currentTime) { - resolve(Math.floor(duration) <= Math.ceil(currentTime)); - }); - }); - } - }]); - - return VideoContainerBase; - }(paella.DomNode); - - paella.VideoContainerBase = VideoContainerBase; // Profile frame strategies - - var ProfileFrameStrategy = /*#__PURE__*/function () { - function ProfileFrameStrategy() { - _classCallCheck(this, ProfileFrameStrategy); - } - - _createClass(ProfileFrameStrategy, [{ - key: "valid", - value: function valid() { - return true; - } - }, { - key: "adaptFrame", - value: function adaptFrame(videoDimensions, frameRect) { - return frameRect; - } - }], [{ - key: "Factory", - value: function Factory() { - var config = paella.player.config; - - try { - var strategyClass = config.player.profileFrameStrategy; - var ClassObject = paella.utils.objectFromString(strategyClass); - var strategy = new ClassObject(); - - if (strategy instanceof paella.ProfileFrameStrategy) { - return strategy; - } - } catch (e) {} - - return null; - } - }]); - - return ProfileFrameStrategy; - }(); - - paella.ProfileFrameStrategy = ProfileFrameStrategy; - - var LimitedSizeProfileFrameStrategy = /*#__PURE__*/function (_ProfileFrameStrategy) { - _inherits(LimitedSizeProfileFrameStrategy, _ProfileFrameStrategy); - - var _super20 = _createSuper(LimitedSizeProfileFrameStrategy); - - function LimitedSizeProfileFrameStrategy() { - _classCallCheck(this, LimitedSizeProfileFrameStrategy); - - return _super20.apply(this, arguments); - } - - _createClass(LimitedSizeProfileFrameStrategy, [{ - key: "adaptFrame", - value: function adaptFrame(videoDimensions, frameRect) { - if (videoDimensions.width < frameRect.width || videoDimensions.height < frameRect.height) { - var frameRectCopy = JSON.parse(JSON.stringify(frameRect)); - frameRectCopy.width = videoDimensions.width; - frameRectCopy.height = videoDimensions.height; - var diff = { - w: frameRect.width - videoDimensions.width, - h: frameRect.height - videoDimensions.height - }; - frameRectCopy.top = frameRectCopy.top + diff.h / 2; - frameRectCopy.left = frameRectCopy.left + diff.w / 2; - return frameRectCopy; - } - - return frameRect; - } - }]); - - return LimitedSizeProfileFrameStrategy; - }(ProfileFrameStrategy); - - paella.LimitedSizeProfileFrameStrategy = LimitedSizeProfileFrameStrategy; - - function updateBuffers() { - // Initial implementation: use the mainStream buffered property - var mainBuffered = this.mainPlayer && this.mainPlayer.buffered; - - if (mainBuffered) { - this._bufferedData = []; - - for (var i = 0; i < mainBuffered.length; ++i) { - this._bufferedData.push({ - start: mainBuffered.start(i), - end: mainBuffered.end(i) - }); - } - } - } - - var StreamProvider = /*#__PURE__*/function () { - function StreamProvider(videoData) { - _classCallCheck(this, StreamProvider); - - this._mainStream = null; - this._videoStreams = []; - this._audioStreams = []; - this._mainPlayer = null; - this._audioPlayer = null; - this._videoPlayers = []; - this._audioPlayers = []; - this._players = []; - this._autoplay = paella.utils.parameters.get('autoplay') == 'true' || this.isLiveStreaming; - this._startTime = 0; - this._bufferedData = []; - var streamProvider = this; - this._buffered = { - start: function start(index) { - if (index < 0 || index >= streamProvider._bufferedData.length) { - throw new Error("Buffered index out of bounds."); - } - - return streamProvider._bufferedData[index].start; - }, - end: function end(index) { - if (index < 0 || index >= streamProvider._bufferedData.length) { - throw new Error("Buffered index out of bounds."); - } - - return streamProvider._bufferedData[index].end; - } - }; - Object.defineProperty(this._buffered, "length", { - get: function get() { - return streamProvider._bufferedData.length; - } - }); - } - - _createClass(StreamProvider, [{ - key: "buffered", - get: function get() { - updateBuffers.apply(this); - return this._buffered; - } - }, { - key: "init", - value: function init(videoData) { - var _this79 = this; - - if (videoData.length == 0) throw Error("Empty video data."); - this._videoData = videoData; - - if (!this._videoData.some(function (stream) { - return stream.role == "master"; - })) { - this._videoData[0].role = "master"; - } - - this._videoData.forEach(function (stream, index) { - stream.type = stream.type || 'video'; - - if (stream.role == 'master') { - _this79._mainStream = stream; - } - - if (stream.type == 'video') { - _this79._videoStreams.push(stream); - } else if (stream.type == 'audio') { - _this79._audioStreams.push(stream); - } - }); - - if (this._videoStreams.length == 0) { - throw new Error("No video streams found. Paella Player requires at least one video stream."); - } // Create video players - - - var autoplay = this.autoplay; - - this._videoStreams.forEach(function (videoStream, index) { - var rect = { - x: 0, - y: 0, - w: 1280, - h: 720 - }; - var player = paella.videoFactory.getVideoObject("video_".concat(index), videoStream, rect); - player.setVideoQualityStrategy(_this79._qualityStrategy); - player.setAutoplay(autoplay); - - if (videoStream == _this79._mainStream) { - _this79._mainPlayer = player; - _this79._audioPlayer = player; - } else { - player.setVolume(0); - } - - _this79._videoPlayers.push(player); - - _this79._players.push(player); - }); // Create audio player - - - this._audioStreams.forEach(function (audioStream, index) { - var player = paella.audioFactory.getAudioObject("audio_".concat(index), audioStream); - player.setAutoplay(autoplay); - - if (player) { - _this79._audioPlayers.push(player); - - _this79._players.push(player); - } - }); - } - }, { - key: "startVideoSync", - value: function startVideoSync(syncProviderPlayer) { - var _this80 = this; - - this._syncProviderPlayer = syncProviderPlayer; - this._audioPlayer = syncProviderPlayer; // The player that provides the synchronization is also used as main audio player. - - this.stopVideoSync(); - console.debug("Start sync to player:"); - console.debug(this._syncProviderPlayer); - var maxDiff = 0.1; - var totalTime = 0; - var numberOfSyncs = 0; - var syncFrequency = 0; - var maxSyncFrequency = 0.2; - - var sync = function sync() { - _this80._syncProviderPlayer.currentTime().then(function (t) { - _this80.players.forEach(function (player) { - if (player != syncProviderPlayer && player.currentTimeSync != null && Math.abs(player.currentTimeSync - t) > maxDiff) { - console.debug("Sync player current time: ".concat(player.currentTimeSync, " to time ").concat(t)); - console.debug(player); - ++numberOfSyncs; - player.setCurrentTime(t); - - if (syncFrequency > maxSyncFrequency) { - maxDiff *= 1.5; - console.log("Maximum syncrhonization frequency reached. Increasing max difference syncronization time to ".concat(maxDiff)); - } - } - }); - }); - - totalTime += 1000; - syncFrequency = numberOfSyncs / (totalTime / 1000); - _this80._syncTimer = setTimeout(function () { - return sync(); - }, 1000); - }; - - this._syncTimer = setTimeout(function () { - return sync(); - }, 1000); - } - }, { - key: "stopVideoSync", - value: function stopVideoSync() { - if (this._syncTimer) { - console.debug("Stop video sync"); - clearTimeout(this._syncTimer); - this._syncTimer = null; - } - } - }, { - key: "loadVideos", - value: function loadVideos() { - var promises = []; - - this._players.forEach(function (player) { - promises.push(player.load()); - }); - - return Promise.all(promises); - } - }, { - key: "startTime", - get: function get() { - return this._startTime; - }, - set: function set(s) { - this._startTime = s; - } - }, { - key: "isMonostream", - get: function get() { - return this._videoStreams.length == 1; - } - }, { - key: "mainStream", - get: function get() { - return this._mainStream; - } - }, { - key: "videoStreams", - get: function get() { - //return this._videoData; - return this._videoStreams; - } - }, { - key: "audioStreams", - get: function get() { - return this._audioStreams; - } - }, { - key: "streams", - get: function get() { - return this._videoStreams.concat(this._audioStreams); - } - }, { - key: "videoPlayers", - get: function get() { - return this._videoPlayers; - } - }, { - key: "audioPlayers", - get: function get() { - return this._audioPlayers; - } - }, { - key: "players", - get: function get() { - return this._videoPlayers.concat(this._audioPlayers); - } - }, { - key: "callPlayerFunction", - value: function callPlayerFunction(fnName) { - var _this81 = this; - - var promises = []; - var functionArguments = []; - - for (var i = 1; i < arguments.length; ++i) { - functionArguments.push(arguments[i]); - } - - this.players.forEach(function (player) { - promises.push(player[fnName].apply(player, functionArguments)); - }); - return new Promise(function (resolve, reject) { - Promise.all(promises).then(function () { - if (fnName == 'play' && !_this81._firstPlay) { - _this81._firstPlay = true; - - if (_this81._startTime) { - _this81.players.forEach(function (p) { - return p.setCurrentTime(_this81._startTime); - }); - } - } - - resolve(); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "mainVideoPlayer", - get: function get() { - return this._mainPlayer; - } - }, { - key: "mainAudioPlayer", - get: function get() { - return this._audioPlayer; - } - }, { - key: "mainPlayer", - get: function get() { - return this.mainVideoPlayer || this.mainAudioPlayer; - } - }, { - key: "isLiveStreaming", - get: function get() { - return paella.player.isLiveStream(); - } - }, { - key: "qualityStrategy", - get: function get() { - return this._qualityStrategy || null; - }, - set: function set(strategy) { - this._qualityStrategy = strategy; - - this._videoPlayers.forEach(function (player) { - player.setVideoQualityStrategy(strategy); - }); - } - }, { - key: "autoplay", - get: function get() { - return this.supportAutoplay && this._autoplay; - }, - set: function set(ap) { - if (!this.supportAutoplay || this.isLiveStreaming) return; - this._autoplay = ap; - - if (this.videoPlayers) { - this.videoPlayers.forEach(function (player) { - return player.setAutoplay(ap); - }); - this.audioPlayers.forEach(function (player) { - return player.setAutoplay(ap); - }); - } - } - }, { - key: "supportAutoplay", - get: function get() { - return this.videoPlayers.every(function (player) { - return player.supportAutoplay(); - }); - } - }]); - - return StreamProvider; - }(); - - paella.StreamProvider = StreamProvider; - - function addVideoWrapper(id, videoPlayer) { - var wrapper = new paella.VideoWrapper(id); - wrapper.addNode(videoPlayer); - this.videoWrappers.push(wrapper); - this.container.addNode(wrapper); - return wrapper; - } - - var VideoContainer = /*#__PURE__*/function (_paella$VideoContaine) { - _inherits(VideoContainer, _paella$VideoContaine); - - var _super21 = _createSuper(VideoContainer); - - function VideoContainer(id) { - var _this82; - - _classCallCheck(this, VideoContainer); - - _this82 = _super21.call(this, id); - _this82._streamProvider = new paella.StreamProvider(); - _this82._ready = false; - _this82._videoWrappers = []; - _this82._container = new paella.DomNode('div', 'playerContainer_videoContainer_container', { - position: 'relative', - display: 'block', - marginLeft: 'auto', - marginRight: 'auto', - width: '1024px', - height: '567px' - }); - - _this82._container.domElement.setAttribute('role', 'main'); - - _this82.addNode(_this82._container); - - _this82.overlayContainer = new paella.VideoOverlay(_this82.domElement); - - _this82.container.addNode(_this82.overlayContainer); - - _this82.setProfileFrameStrategy(paella.ProfileFrameStrategy.Factory()); - - _this82.setVideoQualityStrategy(paella.VideoQualityStrategy.Factory()); - - _this82._audioTag = paella.player.config.player.defaultAudioTag || paella.utils.dictionary.currentLanguage(); - _this82._audioPlayer = null; // Initial volume level - - _this82._volume = paella.utils.cookies.get("volume") ? Number(paella.utils.cookies.get("volume")) : 1; - - if (paella.player.startMuted) { - _this82._volume = 0; - } - - _this82._muted = false; - return _this82; - } // Playback and status functions - - - _createClass(VideoContainer, [{ - key: "streamProvider", - get: function get() { - return this._streamProvider; - } - }, { - key: "ready", - get: function get() { - return this._ready; - } - }, { - key: "isMonostream", - get: function get() { - return this._streamProvider.isMonostream; - } - }, { - key: "trimmingHandler", - get: function get() { - return this._trimmingHandler; - } - }, { - key: "videoWrappers", - get: function get() { - return this._videoWrappers; - } - }, { - key: "container", - get: function get() { - return this._container; - } - }, { - key: "profileFrameStrategy", - get: function get() { - return this._profileFrameStrategy; - } - }, { - key: "sourceData", - get: function get() { - return this._sourceData; - } - }, { - key: "play", - value: function play() { - var _this83 = this; - - var thisClass = this; - return new Promise(function (resolve, reject) { - _this83.ended().then(function (ended) { - if (ended) { - // Wait for seek to complete before requesting play, or risk media freeze-up (i.e. FireFox) - $(document).bind(paella.events.seekToTime, function (event, params) { - $(document).unbind(paella.events.seekToTime); // Now it's safe to call this method again. Ended state evaluates to false because of the seek. - - return thisClass.play(); - }); - _this83._streamProvider.startTime = 0; - - _this83.seekToTime(0); - } else { - _this83.streamProvider.startTime = _this83._startTime; // Call separately from the ended state handling, or risk media freeze-up. - - return _this83.streamProvider.callPlayerFunction('play'); - } - }).then(function () { - _get(_getPrototypeOf(VideoContainer.prototype), "play", _this83).call(_this83); - - resolve(); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "pause", - value: function pause() { - var _this84 = this; - - return new Promise(function (resolve, reject) { - _this84.streamProvider.callPlayerFunction('pause').then(function () { - _get(_getPrototypeOf(VideoContainer.prototype), "pause", _this84).call(_this84); - - resolve(); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "setCurrentTime", - value: function setCurrentTime(time) { - var _this85 = this; - - return new Promise(function (resolve, reject) { - _this85.trimming().then(function (trimmingData) { - if (trimmingData.enabled) { - time += trimmingData.start; - - if (time < trimmingData.start) { - time = trimmingData.start; - } - - if (time > trimmingData.end) { - time = trimmingData.end; - } - } - - return _this85.streamProvider.callPlayerFunction('setCurrentTime', time); - }).then(function () { - return _this85.duration(false); - }).then(function (duration) { - resolve({ - time: time, - duration: duration - }); - }).catch(function (err) { - reject(err); - }); - }); - } - }, { - key: "currentTime", - value: function currentTime() { - var _this86 = this; - - var ignoreTrimming = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return new Promise(function (resolve) { - var trimmingData = null; - var p = ignoreTrimming ? Promise.resolve({ - enabled: false - }) : _this86.trimming(); - p.then(function (t) { - trimmingData = t; - return _this86.masterVideo().currentTime(); - }).then(function (time) { - if (trimmingData.enabled) { - time = time - trimmingData.start; - } - - if (time < 0) time = 0; - resolve(time); - }); - }); - } - }, { - key: "setPlaybackRate", - value: function setPlaybackRate(rate) { - this.streamProvider.callPlayerFunction('setPlaybackRate', rate); - - _get(_getPrototypeOf(VideoContainer.prototype), "setPlaybackRate", this).call(this, rate); - } - }, { - key: "mute", - value: function mute() { - var _this87 = this; - - return new Promise(function (resolve) { - _this87._muted = true; - - _this87._audioPlayer.setVolume(0).then(function () { - paella.events.trigger(paella.events.setVolume, { - master: 0 - }); - resolve(); - }); - }); - } - }, { - key: "unmute", - value: function unmute() { - var _this88 = this; - - return new Promise(function (resolve) { - _this88._muted = false; - - _this88._audioPlayer.setVolume(_this88._volume).then(function () { - paella.events.trigger(paella.events.setVolume, { - master: _this88._volume - }); - resolve(); - }); - }); - } - }, { - key: "muted", - get: function get() { - return this._muted; - } - }, { - key: "setVolume", - value: function setVolume(params) { - var _this89 = this; - - if (_typeof(params) == 'object') { - console.warn("videoContainer.setVolume(): set parameter as object is deprecated"); - return Promise.resolve(); - } else if (params == 0) { - return this.mute(); - } else { - return new Promise(function (resolve, reject) { - paella.utils.cookies.set("volume", params); - _this89._volume = params; - - _this89._audioPlayer.setVolume(params).then(function () { - paella.events.trigger(paella.events.setVolume, { - master: params - }); - resolve(params); - }).catch(function (err) { - reject(err); - }); - }); - } - } - }, { - key: "volume", - value: function volume() { - return this._audioPlayer.volume(); - } - }, { - key: "duration", - value: function duration() { - var _this90 = this; - - var ignoreTrimming = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return new Promise(function (resolve) { - var trimmingData = null; - var p = ignoreTrimming ? Promise.resolve({ - enabled: false - }) : _this90.trimming(); - p.then(function (t) { - trimmingData = t; - return _this90.masterVideo().duration(); - }).then(function (duration) { - if (trimmingData.enabled) { - duration = trimmingData.end - trimmingData.start; - } - - resolve(duration); - }); - }); - } - }, { - key: "paused", - value: function paused() { - return this.masterVideo().isPaused(); - } // Video quality functions - - }, { - key: "getQualities", - value: function getQualities() { - return this.masterVideo().getQualities(); - } - }, { - key: "setQuality", - value: function setQuality(index) { - var qualities = []; - var promises = []; - this.streamProvider.videoPlayers.forEach(function (player) { - var playerData = { - player: player, - promise: player.getQualities() - }; - qualities.push(playerData); - promises.push(playerData.promise); - }); - return new Promise(function (resolve) { - var resultPromises = []; - Promise.all(promises).then(function () { - qualities.forEach(function (data) { - data.promise.then(function (videoQualities) { - var videoQuality = videoQualities.length > index ? index : videoQualities.length - 1; - resultPromises.push(data.player.setQuality(videoQuality)); - }); - }); - return Promise.all(resultPromises); - }).then(function () { - //setTimeout(() => { - paella.events.trigger(paella.events.qualityChanged); - resolve(); //},10); - }); - }); - } - }, { - key: "getCurrentQuality", - value: function getCurrentQuality() { - return this.masterVideo().getCurrentQuality(); - } // Current audio functions - - }, { - key: "audioTag", - get: function get() { - return this._audioTag; - } - }, { - key: "audioPlayer", - get: function get() { - return this._audioPlayer; - } - }, { - key: "getAudioTags", - value: function getAudioTags() { - var _this91 = this; - - return new Promise(function (resolve) { - var lang = []; - var p = _this91.streamProvider.players; - p.forEach(function (player) { - if (player.stream.audioTag) { - lang.push(player.stream.audioTag); - } - }); - resolve(lang); - }); - } - }, { - key: "setAudioTag", - value: function setAudioTag(lang) { - var _this92 = this; - - this.streamProvider.stopVideoSync(); - return new Promise(function (resolve) { - var audioSet = false; - var firstAudioPlayer = null; - var promises = []; - - _this92.streamProvider.players.forEach(function (player) { - if (!firstAudioPlayer) { - firstAudioPlayer = player; - } - - if (!audioSet && player.stream.audioTag == lang) { - audioSet = true; - _this92._audioPlayer = player; - } - - promises.push(player.setVolume(0)); - }); // NOTE: The audio only streams must define a valid audio tag - - - if (!audioSet && _this92.streamProvider.mainVideoPlayer) { - _this92._audioPlayer = _this92.streamProvider.mainVideoPlayer; - } else if (!audioSet && firstAudioPlayer) { - _this92._audioPlayer = firstAudioPlayer; - } - - Promise.all(promises).then(function () { - return _this92._audioPlayer.setVolume(_this92._volume); - }).then(function () { - _this92._audioTag = _this92._audioPlayer.stream.audioTag; - paella.events.trigger(paella.events.audioTagChanged); - - _this92.streamProvider.startVideoSync(_this92.audioPlayer); - - resolve(); - }); - }); - } - }, { - key: "setProfileFrameStrategy", - value: function setProfileFrameStrategy(strategy) { - this._profileFrameStrategy = strategy; - } - }, { - key: "setVideoQualityStrategy", - value: function setVideoQualityStrategy(strategy) { - this.streamProvider.qualityStrategy = strategy; - } - }, { - key: "autoplay", - value: function autoplay() { - return this.streamProvider.autoplay; - } - }, { - key: "supportAutoplay", - value: function supportAutoplay() { - return this.streamProvider.supportAutoplay; - } - }, { - key: "setAutoplay", - value: function setAutoplay() { - var ap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - this.streamProvider.autoplay = ap; - return this.streamProvider.supportAutoplay; - } - }, { - key: "masterVideo", - value: function masterVideo() { - return this.streamProvider.mainVideoPlayer || this.audioPlayer; - } - }, { - key: "getVideoRect", - value: function getVideoRect(videoIndex) { - if (this.videoWrappers.length > videoIndex) { - return this.videoWrappers[videoIndex].getRect(); - } else { - throw new Error("Video wrapper with index ".concat(videoIndex, " not found")); - } - } - }, { - key: "setStreamData", - value: function setStreamData(videoData) { - var _this93 = this; - - var urlParamTime = paella.utils.parameters.get("time"); - var hashParamTime = paella.utils.hashParams.get("time"); - var timeString = hashParamTime ? hashParamTime : urlParamTime ? urlParamTime : "0s"; - var startTime = paella.utils.timeParse.timeToSeconds(timeString); - - if (startTime) { - this._startTime = startTime; - } - - videoData.forEach(function (stream) { - for (var type in stream.sources) { - var source = stream.sources[type]; - source.forEach(function (item) { - if (item.res) { - item.res.w = Number(item.res.w); - item.res.h = Number(item.res.h); - } - }); - } - }); - this._sourceData = videoData; - return new Promise(function (resolve, reject) { - _this93.streamProvider.init(videoData); - - var streamDataAudioTag = null; - videoData.forEach(function (video) { - if (video.audioTag && streamDataAudioTag == null) { - streamDataAudioTag = video.audioTag; - } - - if (video.audioTag == _this93._audioTag) { - streamDataAudioTag = _this93._audioTag; - } - }); - - if (streamDataAudioTag != _this93._audioTag && streamDataAudioTag != null) { - _this93._audioTag = streamDataAudioTag; - } - - _this93.streamProvider.videoPlayers.forEach(function (player, index) { - addVideoWrapper.apply(_this93, ['videoPlayerWrapper_' + index, player]); - player.setAutoplay(_this93.autoplay()); - }); - - _this93.streamProvider.loadVideos().catch(function (err) { - reject(err); - }).then(function () { - return _this93.setAudioTag(_this93.audioTag); - }).then(function () { - var endedTimer = null; - - var setupEndEventTimer = function setupEndEventTimer() { - _this93.stopTimeupdate(); - - if (endedTimer) { - clearTimeout(endedTimer); - endedTimer = null; - } - - endedTimer = setTimeout(function () { - paella.events.trigger(paella.events.ended); - }, 1000); - }; - - var eventBindingObject = _this93.masterVideo().video || _this93.masterVideo().audio; - - $(eventBindingObject).bind('timeupdate', function (evt) { - _this93.trimming().then(function (trimmingData) { - var current = evt.currentTarget.currentTime; - var duration = evt.currentTarget.duration; - - if (trimmingData.enabled) { - current -= trimmingData.start; - duration = trimmingData.end - trimmingData.start; - } - - if (current >= duration) { - _this93.streamProvider.callPlayerFunction('pause'); - - setupEndEventTimer(); - } - }); - }); - paella.events.bind(paella.events.endVideo, function (event) { - setupEndEventTimer(); - }); - _this93._ready = true; - paella.events.trigger(paella.events.videoReady); - var profileToUse = paella.utils.parameters.get('profile') || paella.utils.cookies.get('profile') || paella.profiles.getDefaultProfile(); - - if (paella.profiles.setProfile(profileToUse, false)) { - resolve(); - } else if (!paella.profiles.setProfile(paella.profiles.getDefaultProfile(), false)) { - resolve(); - } - }); - }); - } - }, { - key: "resizePortrait", - value: function resizePortrait() { - var width = paella.player.isFullScreen() == true ? $(window).width() : $(this.domElement).width(); - var relativeSize = new paella.RelativeVideoSize(); - var height = relativeSize.proportionalHeight(width); - this.container.domElement.style.width = width + 'px'; - this.container.domElement.style.height = height + 'px'; - var containerHeight = paella.player.isFullScreen() == true ? $(window).height() : $(this.domElement).height(); - var newTop = containerHeight / 2 - height / 2; - this.container.domElement.style.top = newTop + "px"; - } - }, { - key: "resizeLandscape", - value: function resizeLandscape() { - var height = paella.player.isFullScreen() == true ? $(window).height() : $(this.domElement).height(); - var relativeSize = new paella.RelativeVideoSize(); - var width = relativeSize.proportionalWidth(height); - this.container.domElement.style.width = width + 'px'; - this.container.domElement.style.height = height + 'px'; - this.container.domElement.style.top = '0px'; - } - }, { - key: "onresize", - value: function onresize() { - _get(_getPrototypeOf(VideoContainer.prototype), "onresize", this).call(this); - - var relativeSize = new paella.RelativeVideoSize(); - var aspectRatio = relativeSize.aspectRatio(); - var width = paella.player.isFullScreen() == true ? $(window).width() : $(this.domElement).width(); - var height = paella.player.isFullScreen() == true ? $(window).height() : $(this.domElement).height(); - var containerAspectRatio = width / height; - - if (containerAspectRatio > aspectRatio) { - this.resizeLandscape(); - } else { - this.resizePortrait(); - } //paella.profiles.setProfile(paella.player.selectedProfile,false) - - } // the duration and the current time are returned taking into account the trimming, for example: - // trimming: { enabled: true, start: 10, end: 110 } - // currentTime: 0, > the actual time is 10 - // duration: 100 > the actual duration is (at least) 110 - - }, { - key: "getVideoData", - value: function getVideoData() { - var _this94 = this; - - return new Promise(function (resolve, reject) { - var videoData = { - currentTime: 0, - volume: 0, - muted: _this94.muted, - duration: 0, - paused: false, - audioTag: _this94.audioTag, - trimming: { - enabled: false, - start: 0, - end: 0 - } - }; - - _this94.currentTime().then(function (currentTime) { - videoData.currentTime = currentTime; - return _this94.volume(); - }).then(function (v) { - videoData.volume = v; - return _this94.duration(); - }).then(function (d) { - videoData.duration = d; - return _this94.paused(); - }).then(function (p) { - videoData.paused = p; - return _this94.trimming(); - }).then(function (trimming) { - videoData.trimming = trimming; - resolve(videoData); - }).catch(function (err) { - return reject(err); - }); - }); - } - }]); - - return VideoContainer; - }(paella.VideoContainerBase); - - paella.VideoContainer = VideoContainer; -})(); -/* - Paella HTML 5 Multistream Player - Copyright (C) 2017 Universitat Politècnica de València Licensed under the - Educational Community 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.osedu.org/licenses/ECL-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. -*/ - - -(function () { - var PluginManager = /*#__PURE__*/function () { - function PluginManager() { - var _this95 = this; - - _classCallCheck(this, PluginManager); - - this.targets = null; - this.pluginList = []; - this.eventDrivenPlugins = []; - this.enabledPlugins = []; - this.doResize = true; - this.targets = {}; - paella.events.bind(paella.events.loadPlugins, function (event) { - _this95.loadPlugins("paella.DeferredLoadPlugin"); - }); - var timer = new paella.utils.Timer(function () { - if (paella.player && paella.player.controls && _this95.doResize) paella.player.controls.onresize(); - }, 1000); - timer.repeat = true; - } - - _createClass(PluginManager, [{ - key: "setupPlugin", - value: function setupPlugin(plugin) { - plugin.setup(); - this.enabledPlugins.push(plugin); - - if (eval("plugin instanceof paella.UIPlugin")) { - plugin.checkVisibility(); - } - } - }, { - key: "checkPluginsVisibility", - value: function checkPluginsVisibility() { - this.enabledPlugins.forEach(function (plugin) { - if (eval("plugin instanceof paella.UIPlugin")) { - plugin.checkVisibility(); - } - }); - } - }, { - key: "setTarget", - value: function setTarget(pluginType, target) { - if (target.addPlugin) { - this.targets[pluginType] = target; - } - } - }, { - key: "getTarget", - value: function getTarget(pluginType) { - // PluginManager can handle event-driven events: - if (pluginType == "eventDriven") { - return this; - } else { - var target = this.targets[pluginType]; - return target; - } - } - }, { - key: "registerPlugin", - value: function registerPlugin(plugin) { - // Registra los plugins en una lista y los ordena - this.importLibraries(plugin); - this.pluginList.push(plugin); - this.pluginList.sort(function (a, b) { - return a.getIndex() - b.getIndex(); - }); - } - }, { - key: "importLibraries", - value: function importLibraries(plugin) { - plugin.getDependencies().forEach(function (lib) { - var script = document.createElement('script'); - script.type = "text/javascript"; - script.src = 'javascript/' + lib + '.js'; - document.head.appendChild(script); - }); - } // callback => function(plugin,pluginConfig) - - }, { - key: "loadPlugins", - value: function loadPlugins(pluginBaseClass) { - if (pluginBaseClass != undefined) { - var This = this; - this.foreach(function (plugin, config) { - // Prevent load a plugin twice - if (plugin.isLoaded()) return; - - if (eval("plugin instanceof " + pluginBaseClass)) { - if (config.enabled) { - paella.log.debug("Load plugin (" + pluginBaseClass + "): " + plugin.getName()); - plugin.config = config; - plugin.load(This); - } - } - }); - } - } - }, { - key: "foreach", - value: function foreach(callback) { - var enablePluginsByDefault = false; - var pluginsConfig = {}; - - try { - enablePluginsByDefault = paella.player.config.plugins.enablePluginsByDefault; - } catch (e) {} - - try { - pluginsConfig = paella.player.config.plugins.list; - } catch (e) {} - - this.pluginList.forEach(function (plugin) { - var name = plugin.getName(); - var config = pluginsConfig[name]; - - if (!config) { - config = { - enabled: enablePluginsByDefault - }; - } - - callback(plugin, config); - }); - } - }, { - key: "addPlugin", - value: function addPlugin(plugin) { - var _this96 = this; - - // Prevent add a plugin twice - if (plugin.__added__) return; - plugin.__added__ = true; - plugin.checkEnabled(function (isEnabled) { - if (plugin.type == "eventDriven" && isEnabled) { - paella.pluginManager.setupPlugin(plugin); - - _this96.eventDrivenPlugins.push(plugin); - - var events = plugin.getEvents(); - - var eventBind = function eventBind(event, params) { - plugin.onEvent(event.type, params); - }; - - for (var i = 0; i < events.length; ++i) { - var eventName = events[i]; - paella.events.bind(eventName, eventBind); - } - } - }); - } - }, { - key: "getPlugin", - value: function getPlugin(name) { - for (var i = 0; i < this.pluginList.length; ++i) { - if (this.pluginList[i].getName() == name) return this.pluginList[i]; - } - - return null; - } - }, { - key: "registerPlugins", - value: function registerPlugins() { - g_pluginCallbackList.forEach(function (pluginCallback) { - var PluginClass = pluginCallback(); - var pluginInstance = new PluginClass(); - - if (pluginInstance.getInstanceName()) { - paella.plugins = paella.plugins || {}; - paella.plugins[pluginInstance.getInstanceName()] = pluginInstance; - } - - paella.pluginManager.registerPlugin(pluginInstance); - }); - } - }]); - - return PluginManager; - }(); - - paella.PluginManager = PluginManager; - paella.pluginManager = new paella.PluginManager(); - var g_pluginCallbackList = []; - - paella.addPlugin = function (cb) { - g_pluginCallbackList.push(cb); - }; - - var Plugin = /*#__PURE__*/function () { - function Plugin() { - _classCallCheck(this, Plugin); - } - - _createClass(Plugin, [{ - key: "type", - get: function get() { - return ""; - } - }, { - key: "isLoaded", - value: function isLoaded() { - return this.__loaded__; - } - }, { - key: "getDependencies", - value: function getDependencies() { - return []; - } - }, { - key: "load", - value: function load(pluginManager) { - if (this.__loaded__) return; - this.__loaded__ = true; - var target = pluginManager.getTarget(this.type); - - if (target && target.addPlugin) { - target.addPlugin(this); - } - } - }, { - key: "getInstanceName", - value: function getInstanceName() { - return null; - } - }, { - key: "getRootNode", - value: function getRootNode(id) { - return null; - } - }, { - key: "checkEnabled", - value: function checkEnabled(onSuccess) { - onSuccess(true); - } - }, { - key: "setup", - value: function setup() {} - }, { - key: "getIndex", - value: function getIndex() { - return 0; - } - }, { - key: "getName", - value: function getName() { - return ""; - } - }]); - - return Plugin; - }(); - - paella.Plugin = Plugin; - - var FastLoadPlugin = /*#__PURE__*/function (_paella$Plugin) { - _inherits(FastLoadPlugin, _paella$Plugin); - - var _super22 = _createSuper(FastLoadPlugin); - - function FastLoadPlugin() { - _classCallCheck(this, FastLoadPlugin); - - return _super22.apply(this, arguments); - } - - return _createClass(FastLoadPlugin); - }(paella.Plugin); - - var EarlyLoadPlugin = /*#__PURE__*/function (_paella$Plugin2) { - _inherits(EarlyLoadPlugin, _paella$Plugin2); - - var _super23 = _createSuper(EarlyLoadPlugin); - - function EarlyLoadPlugin() { - _classCallCheck(this, EarlyLoadPlugin); - - return _super23.apply(this, arguments); - } - - return _createClass(EarlyLoadPlugin); - }(paella.Plugin); - - var DeferredLoadPlugin = /*#__PURE__*/function (_paella$Plugin3) { - _inherits(DeferredLoadPlugin, _paella$Plugin3); - - var _super24 = _createSuper(DeferredLoadPlugin); - - function DeferredLoadPlugin() { - _classCallCheck(this, DeferredLoadPlugin); - - return _super24.apply(this, arguments); - } - - return _createClass(DeferredLoadPlugin); - }(paella.Plugin); - - paella.FastLoadPlugin = FastLoadPlugin; - paella.EarlyLoadPlugin = EarlyLoadPlugin; - paella.DeferredLoadPlugin = DeferredLoadPlugin; - - function addMenuItemTabindex(plugin) { - if (plugin.button.tabIndex > 0) { - paella.tabIndex.insertAfter(plugin.button, plugin.menuContent.children); - } - } - - function removeMenuItemTabindexplugin(plugin) { - if (plugin.button.tabIndex > 0) { - paella.tabIndex.removeTabIndex(plugin.menuContent.children); - } - } - - function _hideContainer(identifier, container, swapFocus) { - paella.events.trigger(paella.events.hidePopUp, { - container: container - }); - container.plugin.willHideContent(); - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton) { - removeMenuItemTabindexplugin(container.plugin); - } - - $(container.element).hide(); - $(this.domElement).css({ - width: '0px' - }); - container.button.className = container.button.className.replace(' selected', ''); - this.currentContainerId = -1; - container.plugin.didHideContent(); - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton && swapFocus) { - $(container.button).focus(); - } - } - - function _showContainer(identifier, container, button, swapFocus) { - paella.events.trigger(paella.events.showPopUp, { - container: container - }); - container.plugin.willShowContent(); - container.button.className = container.button.className + ' selected'; - $(container.element).show(); - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton) { - addMenuItemTabindex(container.plugin); - } - - var width = $(container.element).width(); - - if (container.plugin.getAlignment() == 'right') { - var right = $(button.parentElement).width() - $(button).position().left - $(button).width(); - $(this.domElement).css({ - width: width + 'px', - right: right + 'px', - left: '' - }); - } else { - var left = $(button).position().left; - $(this.domElement).css({ - width: width + 'px', - left: left + 'px', - right: '' - }); - } - - this.currentContainerId = identifier; - - if (container.plugin.getButtonType() == paella.ButtonPlugin.type.menuButton && container.plugin.menuContent.children.length > 0 && swapFocus) { - $(container.plugin.menuContent.children[0]).focus(); - } - - container.plugin.didShowContent(); - } - - var PopUpContainer = /*#__PURE__*/function (_paella$DomNode8) { - _inherits(PopUpContainer, _paella$DomNode8); - - var _super25 = _createSuper(PopUpContainer); - - function PopUpContainer(id, className) { - var _this97; - - _classCallCheck(this, PopUpContainer); - - var style = {}; - _this97 = _super25.call(this, 'div', id, style); - _this97.containers = null; - _this97.currentContainerId = -1; - _this97.domElement.className = className; - _this97.containers = {}; - return _this97; - } - - _createClass(PopUpContainer, [{ - key: "hideContainer", - value: function hideContainer(identifier, button) { - var swapFocus = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var container = this.containers[identifier]; - - if (container) { - _hideContainer.apply(this, [identifier, container, swapFocus]); - } - } - }, { - key: "showContainer", - value: function showContainer(identifier, button) { - var swapFocus = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var container = this.containers[identifier]; - - if (container && this.currentContainerId != identifier && this.currentContainerId != -1) { - var prevContainer = this.containers[this.currentContainerId]; - - _hideContainer.apply(this, [this.currentContainerId, prevContainer, swapFocus]); - - _showContainer.apply(this, [identifier, container, button, swapFocus]); - } else if (container && this.currentContainerId == identifier) { - _hideContainer.apply(this, [identifier, container, swapFocus]); - } else if (container) { - _showContainer.apply(this, [identifier, container, button, swapFocus]); - } - } - }, { - key: "registerContainer", - value: function registerContainer(identifier, domElement, button, plugin) { - var containerInfo = { - identifier: identifier, - button: button, - element: domElement, - plugin: plugin - }; - this.containers[identifier] = containerInfo; - - if (plugin.closeOnMouseOut && plugin.closeOnMouseOut()) { - var popUpId = identifier; - var btn = button; - $(domElement).mouseleave(function (evt) { - paella.player.controls.playbackControl().hidePopUp(popUpId, btn); - }); - } // this.domElement.appendChild(domElement); - - - $(domElement).hide(); - button.popUpIdentifier = identifier; - button.sourcePlugin = plugin; - $(button).click(function (event) { - if (!this.plugin.isPopUpOpen()) { - paella.player.controls.playbackControl().showPopUp(this.popUpIdentifier, this, false); - } else { - paella.player.controls.playbackControl().hidePopUp(this.popUpIdentifier, this, false); - } - }); - $(button).keypress(function (event) { - if (event.keyCode == 13 && !this.plugin.isPopUpOpen()) { - if (this.plugin.isPopUpOpen()) { - paella.player.controls.playbackControl().hidePopUp(this.popUpIdentifier, this, true); - } else { - paella.player.controls.playbackControl().showPopUp(this.popUpIdentifier, this, true); - } - } else if (event.keyCode == 27) { - paella.player.controls.playbackControl().hidePopUp(this.popUpIdentifier, this, true); - } - - event.preventDefault(); - }); - $(button).keyup(function (event) { - event.preventDefault(); - }); - plugin.containerManager = this; - } - }]); - - return PopUpContainer; - }(paella.DomNode); - - paella.PopUpContainer = PopUpContainer; - - var TimelineContainer = /*#__PURE__*/function (_paella$PopUpContaine) { - _inherits(TimelineContainer, _paella$PopUpContaine); - - var _super26 = _createSuper(TimelineContainer); - - function TimelineContainer() { - _classCallCheck(this, TimelineContainer); - - return _super26.apply(this, arguments); - } - - _createClass(TimelineContainer, [{ - key: "hideContainer", - value: function hideContainer(identifier, button) { - var container = this.containers[identifier]; - - if (container && this.currentContainerId == identifier) { - paella.events.trigger(paella.events.hidePopUp, { - container: container - }); - container.plugin.willHideContent(); - $(container.element).hide(); - container.button.className = container.button.className.replace(' selected', ''); - this.currentContainerId = -1; - $(this.domElement).css({ - height: '0px' - }); - container.plugin.didHideContent(); - } - } - }, { - key: "showContainer", - value: function showContainer(identifier, button) { - var height = 0; - var container = this.containers[identifier]; - - if (container && this.currentContainerId != identifier && this.currentContainerId != -1) { - var prevContainer = this.containers[this.currentContainerId]; - prevContainer.button.className = prevContainer.button.className.replace(' selected', ''); - container.button.className = container.button.className + ' selected'; - paella.events.trigger(paella.events.hidePopUp, { - container: prevContainer - }); - prevContainer.plugin.willHideContent(); - $(prevContainer.element).hide(); - prevContainer.plugin.didHideContent(); - paella.events.trigger(paella.events.showPopUp, { - container: container - }); - container.plugin.willShowContent(); - $(container.element).show(); - this.currentContainerId = identifier; - height = $(container.element).height(); - $(this.domElement).css({ - height: height + 'px' - }); - container.plugin.didShowContent(); - } else if (container && this.currentContainerId == identifier) { - paella.events.trigger(paella.events.hidePopUp, { - container: container - }); - container.plugin.willHideContent(); - $(container.element).hide(); - container.button.className = container.button.className.replace(' selected', ''); - $(this.domElement).css({ - height: '0px' - }); - this.currentContainerId = -1; - container.plugin.didHideContent(); - } else if (container) { - paella.events.trigger(paella.events.showPopUp, { - container: container - }); - container.plugin.willShowContent(); - container.button.className = container.button.className + ' selected'; - $(container.element).show(); - this.currentContainerId = identifier; - height = $(container.element).height(); - $(this.domElement).css({ - height: height + 'px' - }); - container.plugin.didShowContent(); - } - } - }]); - - return TimelineContainer; - }(paella.PopUpContainer); - - paella.TimelineContainer = TimelineContainer; - - var UIPlugin = /*#__PURE__*/function (_paella$DeferredLoadP) { - _inherits(UIPlugin, _paella$DeferredLoadP); - - var _super27 = _createSuper(UIPlugin); - - function UIPlugin() { - _classCallCheck(this, UIPlugin); - - return _super27.apply(this, arguments); - } - - _createClass(UIPlugin, [{ - key: "ui", - get: function get() { - return this._ui; - }, - set: function set(val) { - this._ui = val; - } - }, { - key: "checkVisibility", - value: function checkVisibility() { - var modes = this.config.visibleOn || [paella.PaellaPlayer.mode.standard, paella.PaellaPlayer.mode.fullscreen, paella.PaellaPlayer.mode.embed]; - var visible = false; - modes.forEach(function (m) { - if (m == paella.player.getPlayerMode()) { - visible = true; - } - }); - - if (visible) { - this.showUI(); - } else { - this.hideUI(); - } - } - }, { - key: "hideUI", - value: function hideUI() { - this.ui.setAttribute('aria-hidden', 'true'); - $(this.ui).hide(); - } - }, { - key: "showUI", - value: function showUI() { - var thisClass = this; - paella.pluginManager.enabledPlugins.forEach(function (p) { - if (p == thisClass) { - thisClass.ui.setAttribute('aria-hidden', 'false'); - $(thisClass.ui).show(); - } - }); - } - }]); - - return UIPlugin; - }(paella.DeferredLoadPlugin); - - paella.UIPlugin = UIPlugin; - - var ButtonPlugin = /*#__PURE__*/function (_paella$UIPlugin) { - _inherits(ButtonPlugin, _paella$UIPlugin); - - var _super28 = _createSuper(ButtonPlugin); - - function ButtonPlugin() { - var _this98; - - _classCallCheck(this, ButtonPlugin); - - _this98 = _super28.call(this); - _this98.subclass = ''; - _this98.container = null; - _this98.containerManager = null; - _this98._domElement = null; - return _this98; - } - - _createClass(ButtonPlugin, [{ - key: "type", - get: function get() { - return 'button'; - } - }, { - key: "getAlignment", - value: function getAlignment() { - return 'left'; // or right - } // Returns the button subclass. - - }, { - key: "getSubclass", - value: function getSubclass() { - return "myButtonPlugin"; - } - }, { - key: "getIconClass", - value: function getIconClass() { - return ""; - } - }, { - key: "addSubclass", - value: function addSubclass($subclass) { - $(this.container).addClass($subclass); - } - }, { - key: "removeSubclass", - value: function removeSubclass($subclass) { - $(this.container).removeClass($subclass); - } - }, { - key: "action", - value: function action(button) {// Implement this if you want to do something when the user push the plugin button - } - }, { - key: "getName", - value: function getName() { - return "ButtonPlugin"; - } - }, { - key: "getMinWindowSize", - value: function getMinWindowSize() { - return this.config.minWindowSize || 0; - } - }, { - key: "buildContent", - value: function buildContent(domElement) {// Override if your plugin - } - }, { - key: "getMenuContent", - value: function getMenuContent() { - return []; - } - }, { - key: "willShowContent", - value: function willShowContent() { - paella.log.debug(this.getName() + " willDisplayContent"); - } - }, { - key: "didShowContent", - value: function didShowContent() { - paella.log.debug(this.getName() + " didDisplayContent"); - } - }, { - key: "willHideContent", - value: function willHideContent() { - paella.log.debug(this.getName() + " willHideContent"); - } - }, { - key: "didHideContent", - value: function didHideContent() { - paella.log.debug(this.getName() + " didHideContent"); - } - }, { - key: "getButtonType", - value: function getButtonType() { - //return paella.ButtonPlugin.type.popUpButton; - //return paella.ButtonPlugin.type.timeLineButton; - //return paella.ButtonPlugin.type.menuButton; - return paella.ButtonPlugin.type.actionButton; - } - }, { - key: "getText", - value: function getText() { - return ""; - } - }, { - key: "getAriaLabel", - value: function getAriaLabel() { - return ""; - } - }, { - key: "setText", - value: function setText(text) { - this.container.innerHTML = '' + paella.AntiXSS.htmlEscape(text) + ''; - - if (this._i) { - this.container.appendChild(this._i); - } - } - }, { - key: "hideButton", - value: function hideButton() { - this.hideUI(); - } - }, { - key: "showButton", - value: function showButton() { - this.showUI(); - } // Utility functions: do not override - - }, { - key: "changeSubclass", - value: function changeSubclass(newSubclass) { - this.subclass = newSubclass; - this.container.className = this.getClassName(); - } - }, { - key: "changeIconClass", - value: function changeIconClass(newClass) { - this._i.className = 'button-icon ' + newClass; - } - }, { - key: "getClassName", - value: function getClassName() { - return paella.ButtonPlugin.kClassName + ' ' + this.getAlignment() + ' ' + this.subclass; - } - }, { - key: "getContainerClassName", - value: function getContainerClassName() { - if (this.getButtonType() == paella.ButtonPlugin.type.timeLineButton) { - return paella.ButtonPlugin.kTimeLineClassName + ' ' + this.getSubclass(); - } else if (this.getButtonType() == paella.ButtonPlugin.type.popUpButton) { - return paella.ButtonPlugin.kPopUpClassName + ' ' + this.getSubclass(); - } else if (this.getButtonType() == paella.ButtonPlugin.type.menuButton) { - return paella.ButtonPlugin.kPopUpClassName + ' menuContainer ' + this.getSubclass(); - } - } - }, { - key: "setToolTip", - value: function setToolTip(message) { - this.button.setAttribute("title", message); - this.button.setAttribute("aria-label", message); - } - }, { - key: "getDefaultToolTip", - value: function getDefaultToolTip() { - return ""; - } - }, { - key: "isPopUpOpen", - value: function isPopUpOpen() { - return this.button.popUpIdentifier == this.containerManager.currentContainerId; - } - }, { - key: "getExpandableContent", - value: function getExpandableContent() { - return null; - } - }, { - key: "expand", - value: function expand() { - if (this._expand) { - $(this._expand).show(); - } - } - }, { - key: "contract", - value: function contract() { - if (this._expand) { - $(this._expand).hide(); - } - } - }, { - key: "menuContent", - get: function get() { - return this._domElement; - }, - set: function set(domElem) { - this._domElement = domElem; - } - }, { - key: "rebuildMenu", - value: function rebuildMenu() { - var _this99 = this; - - function getButtonItem(itemData, plugin) { - var elem = document.createElement('div'); - elem.className = itemData.className + " menuItem"; - - if (itemData.default) { - elem.className += " selected"; - } - - elem.id = itemData.id; - elem.innerText = itemData.title; - - if (itemData.icon) { - elem.style.backgroundImage = "url(".concat(itemData.icon, ")"); - $(elem).addClass('icon'); - } - - elem.data = { - itemData: itemData, - plugin: plugin - }; - - function menuItemSelect(button, data, event) { - data.plugin.menuItemSelected(data.itemData); - var buttons = button.parentElement ? button.parentElement.children : []; - - for (var i = 0; i < buttons.length; ++i) { - $(buttons[i]).removeClass('selected'); - } - - $(button).addClass('selected'); - } - - $(elem).click(function (event) { - menuItemSelect(this, this.data, event); - }); - $(elem).keypress(function (event) { - if (event.keyCode == 13) { - menuItemSelect(this, this.data, event); - } - - event.preventDefault(); - }); - $(elem).keyup(function (event) { - if (event.keyCode == 27) { - paella.player.controls.hidePopUp(this.data.plugin.getName(), null, true); - } - - event.preventDefault(); - }); - return elem; - } - - var menuContent = this.getMenuContent(); - this.menuContent.innerHTML = ""; - menuContent.forEach(function (menuItem) { - _this99.menuContent.appendChild(getButtonItem(menuItem, _this99)); - }); - } - }], [{ - key: "BuildPluginButton", - value: function BuildPluginButton(plugin, id) { - plugin.subclass = plugin.getSubclass(); - var elem = document.createElement('div'); - var ariaLabel = plugin.getAriaLabel() || paella.utils.dictionary.translate(plugin.config.ariaLabel) || ""; - - if (ariaLabel != "") { - elem = document.createElement('button'); - } - - elem.className = plugin.getClassName(); - elem.id = id; - var buttonText = document.createElement('span'); - buttonText.className = "button-text"; - buttonText.innerHTML = paella.AntiXSS.htmlEscape(plugin.getText()); - buttonText.plugin = plugin; - elem.appendChild(buttonText); - - if (ariaLabel) { - var tabIndex = paella.tabIndex.next; - elem.setAttribute("tabindex", tabIndex); - elem.setAttribute("aria-label", ariaLabel); - } - - elem.setAttribute("alt", ""); - elem.plugin = plugin; - plugin.button = elem; - plugin.container = elem; - plugin.ui = elem; - plugin.setToolTip(plugin.getDefaultToolTip()); - var icon = document.createElement('i'); - icon.className = 'button-icon ' + plugin.getIconClass(); - icon.plugin = plugin; - elem.appendChild(icon); - plugin._i = icon; - - function onAction(self) { - paella.userTracking.log("paella:button:action", self.plugin.getName()); - self.plugin.action(self); - } - - $(elem).click(function (event) { - onAction(this); - }); - $(elem).keypress(function (event) { - onAction(this); - event.preventDefault(); - }); - $(elem).focus(function (event) { - plugin.expand(); - }); - return elem; - } - }, { - key: "BuildPluginExpand", - value: function BuildPluginExpand(plugin, id) { - var expandContent = plugin.getExpandableContent(); - - if (expandContent) { - var expand = document.createElement('span'); - expand.plugin = plugin; - expand.className = 'expandable-content ' + plugin.getClassName(); - plugin._expand = expand; - expand.appendChild(expandContent); - $(plugin._expand).hide(); - return expand; - } - - return null; - } - }, { - key: "BuildPluginPopUp", - value: function BuildPluginPopUp(parent, plugin, id) { - plugin.subclass = plugin.getSubclass(); - var elem = document.createElement('div'); - parent.appendChild(elem); - elem.className = plugin.getContainerClassName(); - elem.id = id; - elem.plugin = plugin; - plugin.buildContent(elem); - return elem; - } - }, { - key: "BuildPluginMenu", - value: function BuildPluginMenu(parent, plugin, id) { - plugin.subclass = plugin.getSubclass(); - var elem = document.createElement('div'); - parent.appendChild(elem); - elem.className = plugin.getContainerClassName(); - elem.id = id; - elem.plugin = plugin; - plugin.menuContent = elem; - plugin.rebuildMenu(elem); - return elem; - } - }]); - - return ButtonPlugin; - }(paella.UIPlugin); - - paella.ButtonPlugin = ButtonPlugin; - paella.ButtonPlugin.alignment = { - left: 'left', - right: 'right' - }; - paella.ButtonPlugin.kClassName = 'buttonPlugin'; - paella.ButtonPlugin.kPopUpClassName = 'buttonPluginPopUp'; - paella.ButtonPlugin.kTimeLineClassName = 'buttonTimeLine'; - paella.ButtonPlugin.type = { - actionButton: 1, - popUpButton: 2, - timeLineButton: 3, - menuButton: 4 - }; - - var VideoOverlayButtonPlugin = /*#__PURE__*/function (_paella$ButtonPlugin) { - _inherits(VideoOverlayButtonPlugin, _paella$ButtonPlugin); - - var _super29 = _createSuper(VideoOverlayButtonPlugin); - - function VideoOverlayButtonPlugin() { - _classCallCheck(this, VideoOverlayButtonPlugin); - - return _super29.apply(this, arguments); - } - - _createClass(VideoOverlayButtonPlugin, [{ - key: "type", - get: function get() { - return 'videoOverlayButton'; - } // Returns the button subclass. - - }, { - key: "getSubclass", - value: function getSubclass() { - return "myVideoOverlayButtonPlugin" + " " + this.getAlignment(); - } - }, { - key: "action", - value: function action(button) {// Implement this if you want to do something when the user push the plugin button - } - }, { - key: "getName", - value: function getName() { - return "VideoOverlayButtonPlugin"; - } - }, { - key: "tabIndex", - get: function get() { - return -1; - } - }]); - - return VideoOverlayButtonPlugin; - }(paella.ButtonPlugin); - - paella.VideoOverlayButtonPlugin = VideoOverlayButtonPlugin; - - var EventDrivenPlugin = /*#__PURE__*/function (_paella$EarlyLoadPlug) { - _inherits(EventDrivenPlugin, _paella$EarlyLoadPlug); - - var _super30 = _createSuper(EventDrivenPlugin); - - function EventDrivenPlugin() { - var _this100; - - _classCallCheck(this, EventDrivenPlugin); - - _this100 = _super30.call(this); - - var events = _this100.getEvents(); - - for (var i = 0; i < events.length; ++i) { - var event = events[i]; - - if (event == paella.events.loadStarted) { - _this100.onEvent(paella.events.loadStarted); - } - } - - return _this100; - } - - _createClass(EventDrivenPlugin, [{ - key: "type", - get: function get() { - return 'eventDriven'; - } - }, { - key: "getEvents", - value: function getEvents() { - return []; - } - }, { - key: "onEvent", - value: function onEvent(eventType, params) {} - }, { - key: "getName", - value: function getName() { - return "EventDrivenPlugin"; - } - }]); - - return EventDrivenPlugin; - }(paella.EarlyLoadPlugin); - - paella.EventDrivenPlugin = EventDrivenPlugin; -})(); - -(function () { - var VideoCanvas = /*#__PURE__*/function () { - function VideoCanvas(stream) { - _classCallCheck(this, VideoCanvas); - - this._stream = stream; - } - - _createClass(VideoCanvas, [{ - key: "loadVideo", - value: function loadVideo(videoPlugin, stream) { - return Promise.reject(new Error("Not implemented")); - } - }, { - key: "allowZoom", - value: function allowZoom() { - return true; - } - }]); - - return VideoCanvas; - }(); - - paella.VideoCanvas = VideoCanvas; - - function initWebGLCanvas() { - if (!paella.WebGLCanvas) { - var WebGLCanvas = /*#__PURE__*/function (_bg$app$WindowControl) { - _inherits(WebGLCanvas, _bg$app$WindowControl); - - var _super31 = _createSuper(WebGLCanvas); - - function WebGLCanvas(stream) { - var _this101; - - _classCallCheck(this, WebGLCanvas); - - _this101 = _super31.call(this); - _this101._stream = stream; - return _this101; - } - - _createClass(WebGLCanvas, [{ - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "video", - get: function get() { - return this.texture ? this.texture.video : null; - } - }, { - key: "camera", - get: function get() { - return this._camera; - } - }, { - key: "texture", - get: function get() { - return this._texture; - } - }, { - key: "loaded", - value: function loaded() { - var _this102 = this; - - return new Promise(function (resolve) { - var checkLoaded = function checkLoaded() { - if (_this102.video) { - resolve(_this102); - } else { - setTimeout(checkLoaded, 100); - } - }; - - checkLoaded(); - }); - } - }, { - key: "loadVideo", - value: function loadVideo(videoPlugin, stream) { - return Promise.reject(new Error("Not implemented")); - } - }, { - key: "allowZoom", - value: function allowZoom() { - return false; - } // WebGL engine functions - - }, { - key: "registerPlugins", - value: function registerPlugins() { - bg.base.Loader.RegisterPlugin(new bg.base.TextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VideoTextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VWGLBLoaderPlugin()); - } - }, { - key: "loadVideoTexture", - value: function loadVideoTexture() { - return bg.base.Loader.Load(this.gl, this.stream.src); - } - }, { - key: "buildVideoSurface", - value: function buildVideoSurface(sceneRoot, videoTexture) { - var sphere = bg.scene.PrimitiveFactory.Sphere(this.gl, 1, 50); - var sphereNode = new bg.scene.Node(this.gl); - sphereNode.addComponent(sphere); - sphere.getMaterial(0).texture = videoTexture; - sphere.getMaterial(0).lightEmission = 0; - sphere.getMaterial(0).lightEmissionMaskInvert = false; - sphere.getMaterial(0).cullFace = false; - sphereNode.addComponent(new bg.scene.Transform(bg.Matrix4.Scale(1, -1, 1))); - sceneRoot.addChild(sphereNode); - } - }, { - key: "buildCamera", - value: function buildCamera() { - var cameraNode = new bg.scene.Node(this.gl, "Camera"); - var camera = new bg.scene.Camera(); - cameraNode.addComponent(camera); - cameraNode.addComponent(new bg.scene.Transform()); - var projection = new bg.scene.OpticalProjectionStrategy(); - projection.far = 100; - projection.focalLength = 55; - camera.projectionStrategy = projection; - var oc = new bg.manipulation.OrbitCameraController(); - oc.maxPitch = 90; - oc.minPitch = -90; - oc.maxDistance = 0; - oc.minDistance = 0; - this._cameraController = oc; - cameraNode.addComponent(oc); - return cameraNode; - } - }, { - key: "buildScene", - value: function buildScene() { - var _this103 = this; - - this._root = new bg.scene.Node(this.gl, "Root node"); - this.registerPlugins(); - this.loadVideoTexture().then(function (texture) { - _this103._texture = texture; - - _this103.buildVideoSurface(_this103._root, texture); - }); - var lightNode = new bg.scene.Node(this.gl, "Light"); - var light = new bg.base.Light(); - light.ambient = bg.Color.White(); - light.diffuse = bg.Color.Black(); - light.specular = bg.Color.Black(); - lightNode.addComponent(new bg.scene.Light(light)); - - this._root.addChild(lightNode); - - var cameraNode = this.buildCamera(); - this._camera = cameraNode.component("bg.scene.Camera"); - - this._root.addChild(cameraNode); - } - }, { - key: "init", - value: function init() { - bg.Engine.Set(new bg.webgl1.Engine(this.gl)); - this.buildScene(); - this._renderer = bg.render.Renderer.Create(this.gl, bg.render.RenderPath.FORWARD); - this._inputVisitor = new bg.scene.InputVisitor(); - } - }, { - key: "frame", - value: function frame(delta) { - if (this.texture) { - this.texture.update(); - } - - this._renderer.frame(this._root, delta); - - this.postReshape(); - } - }, { - key: "display", - value: function display() { - this._renderer.display(this._root, this._camera); - } - }, { - key: "reshape", - value: function reshape(width, height) { - this._camera.viewport = new bg.Viewport(0, 0, width, height); - - if (!this._camera.projectionStrategy) { - this._camera.projection.perspective(60, this._camera.viewport.aspectRatio, 0.1, 100); - } - } - }, { - key: "mouseDrag", - value: function mouseDrag(evt) { - this._inputVisitor.mouseDrag(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseWheel", - value: function mouseWheel(evt) { - this._inputVisitor.mouseWheel(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "touchMove", - value: function touchMove(evt) { - this._inputVisitor.touchMove(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseDown", - value: function mouseDown(evt) { - this._inputVisitor.mouseDown(this._root, evt); - } - }, { - key: "touchStar", - value: function touchStar(evt) { - this._inputVisitor.touchStar(this._root, evt); - } - }, { - key: "mouseUp", - value: function mouseUp(evt) { - this._inputVisitor.mouseUp(this._root, evt); - } - }, { - key: "mouseMove", - value: function mouseMove(evt) { - this._inputVisitor.mouseMove(this._root, evt); - } - }, { - key: "mouseOut", - value: function mouseOut(evt) { - this._inputVisitor.mouseOut(this._root, evt); - } - }, { - key: "touchEnd", - value: function touchEnd(evt) { - this._inputVisitor.touchEnd(this._root, evt); - } - }]); - - return WebGLCanvas; - }(bg.app.WindowController); - - paella.WebGLCanvas = WebGLCanvas; - } - } - - function buildVideoCanvas(stream) { - if (!paella.WebGLCanvas) { - var WebGLCanvas = /*#__PURE__*/function (_bg$app$WindowControl2) { - _inherits(WebGLCanvas, _bg$app$WindowControl2); - - var _super32 = _createSuper(WebGLCanvas); - - function WebGLCanvas(stream) { - var _this104; - - _classCallCheck(this, WebGLCanvas); - - _this104 = _super32.call(this); - _this104._stream = stream; - return _this104; - } - - _createClass(WebGLCanvas, [{ - key: "stream", - get: function get() { - return this._stream; - } - }, { - key: "video", - get: function get() { - return this.texture ? this.texture.video : null; - } - }, { - key: "camera", - get: function get() { - return this._camera; - } - }, { - key: "texture", - get: function get() { - return this._texture; - } - }, { - key: "allowZoom", - value: function allowZoom() { - return false; - } - }, { - key: "loaded", - value: function loaded() { - var _this105 = this; - - return new Promise(function (resolve) { - var checkLoaded = function checkLoaded() { - if (_this105.video) { - resolve(_this105); - } else { - setTimeout(checkLoaded, 100); - } - }; - - checkLoaded(); - }); - } - }, { - key: "registerPlugins", - value: function registerPlugins() { - bg.base.Loader.RegisterPlugin(new bg.base.TextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VideoTextureLoaderPlugin()); - bg.base.Loader.RegisterPlugin(new bg.base.VWGLBLoaderPlugin()); - } - }, { - key: "loadVideoTexture", - value: function loadVideoTexture() { - return bg.base.Loader.Load(this.gl, this.stream.src); - } - }, { - key: "buildVideoSurface", - value: function buildVideoSurface(sceneRoot, videoTexture) { - var sphere = bg.scene.PrimitiveFactory.Sphere(this.gl, 1, 50); - var sphereNode = new bg.scene.Node(this.gl); - sphereNode.addComponent(sphere); - sphere.getMaterial(0).texture = videoTexture; - sphere.getMaterial(0).lightEmission = 0; - sphere.getMaterial(0).lightEmissionMaskInvert = false; - sphere.getMaterial(0).cullFace = false; - sphereNode.addComponent(new bg.scene.Transform(bg.Matrix4.Scale(1, -1, 1))); - sceneRoot.addChild(sphereNode); - } - }, { - key: "buildCamera", - value: function buildCamera() { - var cameraNode = new bg.scene.Node(this.gl, "Camera"); - var camera = new bg.scene.Camera(); - cameraNode.addComponent(camera); - cameraNode.addComponent(new bg.scene.Transform()); - var projection = new bg.scene.OpticalProjectionStrategy(); - projection.far = 100; - projection.focalLength = 55; - camera.projectionStrategy = projection; - var oc = new bg.manipulation.OrbitCameraController(); - oc.maxPitch = 90; - oc.minPitch = -90; - oc.maxDistance = 0; - oc.minDistance = 0; - this._cameraController = oc; - cameraNode.addComponent(oc); - return cameraNode; - } - }, { - key: "buildScene", - value: function buildScene() { - var _this106 = this; - - this._root = new bg.scene.Node(this.gl, "Root node"); - this.registerPlugins(); - this.loadVideoTexture().then(function (texture) { - _this106._texture = texture; - - _this106.buildVideoSurface(_this106._root, texture); - }); - var lightNode = new bg.scene.Node(this.gl, "Light"); - var light = new bg.base.Light(); - light.ambient = bg.Color.White(); - light.diffuse = bg.Color.Black(); - light.specular = bg.Color.Black(); - lightNode.addComponent(new bg.scene.Light(light)); - - this._root.addChild(lightNode); - - var cameraNode = this.buildCamera(); - this._camera = cameraNode.component("bg.scene.Camera"); - - this._root.addChild(cameraNode); - } - }, { - key: "init", - value: function init() { - bg.Engine.Set(new bg.webgl1.Engine(this.gl)); - this.buildScene(); - this._renderer = bg.render.Renderer.Create(this.gl, bg.render.RenderPath.FORWARD); - this._inputVisitor = new bg.scene.InputVisitor(); - } - }, { - key: "frame", - value: function frame(delta) { - if (this.texture) { - this.texture.update(); - } - - this._renderer.frame(this._root, delta); - - this.postReshape(); - } - }, { - key: "display", - value: function display() { - this._renderer.display(this._root, this._camera); - } - }, { - key: "reshape", - value: function reshape(width, height) { - this._camera.viewport = new bg.Viewport(0, 0, width, height); - - if (!this._camera.projectionStrategy) { - this._camera.projection.perspective(60, this._camera.viewport.aspectRatio, 0.1, 100); - } - } - }, { - key: "mouseDrag", - value: function mouseDrag(evt) { - this._inputVisitor.mouseDrag(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseWheel", - value: function mouseWheel(evt) { - this._inputVisitor.mouseWheel(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "touchMove", - value: function touchMove(evt) { - this._inputVisitor.touchMove(this._root, evt); - - this.postRedisplay(); - } - }, { - key: "mouseDown", - value: function mouseDown(evt) { - this._inputVisitor.mouseDown(this._root, evt); - } - }, { - key: "touchStar", - value: function touchStar(evt) { - this._inputVisitor.touchStar(this._root, evt); - } - }, { - key: "mouseUp", - value: function mouseUp(evt) { - this._inputVisitor.mouseUp(this._root, evt); - } - }, { - key: "mouseMove", - value: function mouseMove(evt) { - this._inputVisitor.mouseMove(this._root, evt); - } - }, { - key: "mouseOut", - value: function mouseOut(evt) { - this._inputVisitor.mouseOut(this._root, evt); - } - }, { - key: "touchEnd", - value: function touchEnd(evt) { - this._inputVisitor.touchEnd(this._root, evt); - } - }]); - - return WebGLCanvas; - }(bg.app.WindowController); - - paella.WebGLCanvas = WebGLCanvas; - } - - return paella.WebGLCanvas; - } - - var g_canvasCallbacks = {}; - - paella.addCanvasPlugin = function (canvasType, webglSupport, mouseEventsSupport, canvasPluginCallback) { - g_canvasCallbacks[canvasType] = { - callback: canvasPluginCallback, - webglSupport: webglSupport, - mouseEventsSupport: mouseEventsSupport - }; - }; - - function loadWebGLDeps() { - return new Promise(function (resolve) { - if (!window.$paella_bg) { - paella.require("".concat(paella.baseUrl, "javascript/bg2e-es2015.js")).then(function () { - window.$paella_bg = bg; - buildVideoCanvas(); // loadWebGLDeps(); - - resolve(window.$paella_bg); - }); - } else { - resolve(window.$paella_bg); - } - }); - } - - function loadCanvasPlugin(canvasType) { - return new Promise(function (resolve, reject) { - var callbackData = g_canvasCallbacks[canvasType]; - - if (callbackData) { - (callbackData.webglSupport ? loadWebGLDeps() : Promise.resolve()).then(function () { - resolve(callbackData.callback()); - }).catch(function (err) { - reject(err); - }); - } else { - reject(new Error("No such canvas type: \"".concat(canvasType, "\""))); - } - }); - } - - paella.getVideoCanvas = function (type) { - return new Promise(function (resolve, reject) { - var canvasData = g_canvasCallbacks[type]; - - if (!canvasData) { - reject(new Error("No such canvas type: " + type)); - } else { - if (canvasData.webglSupport) { - loadWebGLDeps().then(function () { - resolve(canvasData.callback()); - }); - } else { - resolve(canvasData.callback()); - } - } - }); - }; - - paella.getVideoCanvasData = function (type) { - return g_canvasCallbacks[type]; - }; // Standard
          • ' - , minLength: 1 - } - - $.fn.typeahead.Constructor = Typeahead - - - /* TYPEAHEAD NO CONFLICT - * =================== */ - - $.fn.typeahead.noConflict = function () { - $.fn.typeahead = old - return this - } - - - /* TYPEAHEAD DATA-API - * ================== */ - - $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) { - var $this = $(this) - if ($this.data('typeahead')) return - $this.typeahead($this.data()) - }) - -}(window.jQuery); diff --git a/node_modules/paellaplayer/build/player/resources/bootstrap/js/bootstrap.min.js b/node_modules/paellaplayer/build/player/resources/bootstrap/js/bootstrap.min.js deleted file mode 100755 index f6736a860..000000000 --- a/node_modules/paellaplayer/build/player/resources/bootstrap/js/bootstrap.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/** -* Bootstrap.js by @fat & @mdo -* plugins: bootstrap-transition.js, bootstrap-modal.js, bootstrap-dropdown.js, bootstrap-scrollspy.js, bootstrap-tab.js, bootstrap-tooltip.js, bootstrap-popover.js, bootstrap-affix.js, bootstrap-alert.js, bootstrap-button.js, bootstrap-collapse.js, bootstrap-carousel.js, bootstrap-typeahead.js -* Copyright 2012 Twitter, Inc. -* http://www.apache.org/licenses/LICENSE-2.0.txt -*/ -!function(a){a(function(){a.support.transition=function(){var a=function(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in b)if(a.style[c]!==undefined)return b[c]}();return a&&{end:a}}()})}(window.jQuery),!function(a){var b=function(b,c){this.options=c,this.$element=a(b).delegate('[data-dismiss="modal"]',"click.dismiss.modal",a.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};b.prototype={constructor:b,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var b=this,c=a.Event("show");this.$element.trigger(c);if(this.isShown||c.isDefaultPrevented())return;this.isShown=!0,this.escape(),this.backdrop(function(){var c=a.support.transition&&b.$element.hasClass("fade");b.$element.parent().length||b.$element.appendTo(document.body),b.$element.show(),c&&b.$element[0].offsetWidth,b.$element.addClass("in").attr("aria-hidden",!1),b.enforceFocus(),c?b.$element.one(a.support.transition.end,function(){b.$element.focus().trigger("shown")}):b.$element.focus().trigger("shown")})},hide:function(b){b&&b.preventDefault();var c=this;b=a.Event("hide"),this.$element.trigger(b);if(!this.isShown||b.isDefaultPrevented())return;this.isShown=!1,this.escape(),a(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),a.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var b=this;a(document).on("focusin.modal",function(a){b.$element[0]!==a.target&&!b.$element.has(a.target).length&&b.$element.focus()})},escape:function(){var a=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(b){b.which==27&&a.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var b=this,c=setTimeout(function(){b.$element.off(a.support.transition.end),b.hideModal()},500);this.$element.one(a.support.transition.end,function(){clearTimeout(c),b.hideModal()})},hideModal:function(){var a=this;this.$element.hide(),this.backdrop(function(){a.removeBackdrop(),a.$element.trigger("hidden")})},removeBackdrop:function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},backdrop:function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;this.$backdrop=a('