Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
cqiang1993
AR.js
提交
639d6889
A
AR.js
项目概览
cqiang1993
/
AR.js
与 Fork 源项目一致
从无法访问的项目Fork
通知
2
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
A
AR.js
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
提交
Issue看板
体验新版 GitCode,发现更多精彩内容 >>
提交
639d6889
编写于
9月 24, 2018
作者:
J
Jerome Etienne
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
Last commit before release
上级
2f426738
变更
10
显示空白变更内容
内联
并排
Showing
10 changed file
with
10 addition
and
10 deletion
+10
-10
CHANGELOG.md
CHANGELOG.md
+1
-1
README.md
README.md
+1
-1
aframe/build/aframe-ar.js
aframe/build/aframe-ar.js
+1
-1
aframe/build/aframe-ar.min.js
aframe/build/aframe-ar.min.js
+1
-1
package.json
package.json
+1
-1
three.js/build/ar.js
three.js/build/ar.js
+1
-1
three.js/build/ar.min.js
three.js/build/ar.min.js
+1
-1
three.js/contribs/portableAR.js/build/portable-ar.js
three.js/contribs/portableAR.js/build/portable-ar.js
+1
-1
three.js/contribs/portableAR.js/build/portable-ar.min.js
three.js/contribs/portableAR.js/build/portable-ar.min.js
+1
-1
three.js/src/threex/threex-artoolkitcontext.js
three.js/src/threex/threex-artoolkitcontext.js
+1
-1
未找到文件。
CHANGELOG.md
浏览文件 @
639d6889
# 1.6.2
-dev
# 1.6.2
-
Adds TravisCI config with NPM deployment configured - thanks @joestrong -
[
#344
](
https://github.com/jeromeetienne/AR.js/pull/344
)
...
...
README.md
浏览文件 @
639d6889
...
...
@@ -261,7 +261,7 @@ git checkout master
git merge dev
# tag the release
git tag 1.6.
1
git tag 1.6.
2
# push the tag on github
git push origin
--tags
...
...
aframe/build/aframe-ar.js
浏览文件 @
639d6889
...
...
@@ -5254,7 +5254,7 @@ Object.assign( ARjs.Context.prototype, THREE.EventDispatcher.prototype );
// ARjs.Context.baseURL = '../'
// default to github page
ARjs.Context.baseURL = 'https://jeromeetienne.github.io/AR.js/three.js/'
ARjs.Context.REVISION = '1.6.
1
'
ARjs.Context.REVISION = '1.6.
2
'
aframe/build/aframe-ar.min.js
浏览文件 @
639d6889
因为 它太大了无法显示 source diff 。你可以改为
查看blob
。
package.json
浏览文件 @
639d6889
{
"name"
:
"ar.js"
,
"version"
:
"1.6.
1
"
,
"version"
:
"1.6.
2
"
,
"description"
:
"Efficient Augmented Reality for the Web"
,
"main"
:
""
,
"scripts"
:
{
...
...
three.js/build/ar.js
浏览文件 @
639d6889
...
...
@@ -5254,7 +5254,7 @@ Object.assign( ARjs.Context.prototype, THREE.EventDispatcher.prototype );
// ARjs.Context.baseURL = '../'
// default to github page
ARjs.Context.baseURL = 'https://jeromeetienne.github.io/AR.js/three.js/'
ARjs.Context.REVISION = '1.6.
1
'
ARjs.Context.REVISION = '1.6.
2
'
three.js/build/ar.min.js
浏览文件 @
639d6889
...
...
@@ -25,6 +25,6 @@ n=0;o=m;while(1){if((c[o>>2]|0)==(p|0))c[o>>2]=j;n=n+1|0;if((n|0)>=(r|0))break;e
a[I+v>>0]=F>>>31;F=(F|0)>-1?F:0-F|0;v=v+-1|0;y=(F|0)<(y|0)?F:y}if((z|0)>0)z=z+-1|0;else break}if((D|0)>0)D=D+-1|0;else break}break}case 3:{v=119;y=255;D=13;while(1){C=D+-3|0;B=D&-2;A=(B|0)==12;B=(B|0)==0;z=0;do{if(((z+-3|C)>>>0>=8?!(A&z>>>0<2|(z|D)>>>0<2):0)?!(B&(z&-2|0)==12):0){F=(d[K+((z*14|0)+D)>>0]|0)-H|0;a[I+v>>0]=F>>>31;F=(F|0)>-1?F:0-F|0;v=v+-1|0;y=(F|0)<(y|0)?F:y}z=z+1|0}while((z|0)!=14);if((D|0)>0)D=D+-1|0;else break}break}default:y=255}c[t>>2]=G;h[u>>3]=(y|0)>30?1.0:+(y|0)/30.0;y=Ie(2830,0,0,I,J)|0;if((y|0)<0){y=-4;v=0;z=0}else{if(w)c[w>>2]=y;z=J;y=0;v=c[z>>2]|0;z=c[z+4>>2]|0}}else{c[t>>2]=0;h[u>>3]=-1.0;y=-2;v=0;z=0}while(0);if((y|0)<0){c[s>>2]=-1;break}if((v|0)==-1&(z|0)==-1){c[s>>2]=-1;y=-5;break}c[s>>2]=(v&-32768|0)==0&0==0?v&32767:0;if(!x)y=0;else{y=x;c[y>>2]=v;c[y+4>>2]=z;y=0}}else y=1;while(0);b:do switch(f|0){case 0:case 1:case 3:case 4:{if(!b){c[p>>2]=-1;v=-1;break b}v=b+28|0;z=c[v>>2]|0;A=z<<2;switch(f|0){case 0:case 3:if((Ee(e,0,z,A,g,j,k,l,m,n,o,K)|0)<0){c[p>>2]=-1;v=-6;break b}else{v=Ge(b,0,K,c[v>>2]|0,p,q,r)|0;break b}default:if((Ee(e,1,z,A,g,j,k,l,m,n,o,K)|0)<0){c[p>>2]=-1;v=-6;break b}else{v=Ge(b,1,K,c[v>>2]|0,p,q,r)|0;break b}}}default:v=1}while(0);if((y|0)!=1){if((v|0)!=1)y=(v&y|0)<0?v:0}else y=v;i=L;return y|0}function _j(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+16|0;b=k+8|0;h=k+4|0;d=k;c[h>>2]=a;do if(a>>>0>=212){g=(a>>>0)/210|0;e=g*210|0;c[d>>2]=a-e;b=($j(3712,3904,d,b)|0)-3712>>2;f=b;b=(c[3712+(b<<2)>>2]|0)+e|0;a:while(1){e=5;while(1){if(e>>>0>=47){e=211;j=8;break}d=c[3520+(e<<2)>>2]|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=106;break a}if((b|0)==($(a,d)|0))break;else e=e+1|0}b:do if((j|0)==8)while(1){j=0;d=(b>>>0)/(e>>>0)|0;if(d>>>0<e>>>0){j=105;break a}if((b|0)==($(d,e)|0))break b;d=e+10|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+12|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+16|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+18|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+22|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+28|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+30|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+36|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+40|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+42|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+46|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+52|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+58|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+60|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+66|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+70|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+72|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+78|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+82|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+88|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+96|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+100|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+102|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+106|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+108|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+112|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+120|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+126|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+130|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+136|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+138|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+142|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+148|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+150|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+156|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+162|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+166|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+168|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+172|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+178|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+180|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+186|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+190|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+192|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+196|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+198|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+208|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break;else{e=e+210|0;j=8}}while(0);e=f+1|0;b=(e|0)==48;e=b?0:e;b=(b&1)+g|0;f=e;g=b;b=(c[3712+(e<<2)>>2]|0)+(b*210|0)|0}if((j|0)==105){c[h>>2]=b;break}else if((j|0)==106){c[h>>2]=b;break}}else b=c[($j(3520,3712,h,b)|0)>>2]|0;while(0);i=k;return b|0}function $j(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0;f=c[d>>2]|0;e=a;d=b-a>>2;a:while(1){while(1){if(!d)break a;a=(d|0)/2|0;if((c[e+(a<<2)>>2]|0)>>>0<f>>>0)break;else d=a}e=e+(a+1<<2)|0;d=d+-1-a|0}return e|0}function ak(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0;if(e>>>0>4294967279)oi(b);if(e>>>0<11){a[b>>0]=e<<1;b=b+1|0}else{g=e+16&-16;f=Kh(g)|0;c[b+8>>2]=f;c[b>>2]=g|1;c[b+4>>2]=e;b=f}ik(b|0,d|0,e|0)|0;a[b+e>>0]=0;return}function bk(b){b=b|0;if(a[b>>0]&1)Lh(c[b+8>>2]|0);return}function ck(){}function dk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;d=b-d-(c>>>0>a>>>0|0)>>>0;return(D=d,a-c>>>0|0)|0}function ek(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0;f=b+e|0;if((e|0)>=20){d=d&255;h=b&3;i=d|d<<8|d<<16|d<<24;g=f&~3;if(h){h=b+4-h|0;while((b|0)<(h|0)){a[b>>0]=d;b=b+1|0}}while((b|0)<(g|0)){c[b>>2]=i;b=b+4|0}}while((b|0)<(f|0)){a[b>>0]=d;b=b+1|0}return b-e|0}function fk(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){D=b<<c|(a&(1<<c)-1<<32-c)>>>32-c;return a<<c}D=a<<c-32;return 0}function gk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;c=a+c>>>0;return(D=b+d+(c>>>0<a>>>0|0)>>>0,c|0)|0}function hk(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){D=b>>>c;return a>>>c|(b&(1<<c)-1)<<32-c}D=0;return b>>>c-32|0}function ik(b,d,e){b=b|0;d=d|0;e=e|0;var f=0;if((e|0)>=4096)return Xa(b|0,d|0,e|0)|0;f=b|0;if((b&3)==(d&3)){while(b&3){if(!e)return f|0;a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}while((e|0)>=4){c[b>>2]=c[d>>2];b=b+4|0;d=d+4|0;e=e-4|0}}while((e|0)>0){a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}return f|0}function jk(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){D=b>>c;return a>>>c|(b&(1<<c)-1)<<32-c}D=(b|0)<0?-1:0;return b>>c-32|0}function kk(b){b=b|0;var c=0;c=a[m+(b&255)>>0]|0;if((c|0)<8)return c|0;c=a[m+(b>>8&255)>>0]|0;if((c|0)<8)return c+8|0;c=a[m+(b>>16&255)>>0]|0;if((c|0)<8)return c+16|0;return(a[m+(b>>>24)>>0]|0)+24|0}function lk(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0;f=a&65535;e=b&65535;c=$(e,f)|0;d=a>>>16;a=(c>>>16)+($(e,d)|0)|0;e=b>>>16;b=$(e,f)|0;return(D=(a>>>16)+($(e,d)|0)+(((a&65535)+b|0)>>>16)|0,a+b<<16|c&65535|0)|0}function mk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0;j=b>>31|((b|0)<0?-1:0)<<1;i=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;f=d>>31|((d|0)<0?-1:0)<<1;e=((d|0)<0?-1:0)>>31|((d|0)<0?-1:0)<<1;h=dk(j^a,i^b,j,i)|0;g=D;a=f^j;b=e^i;return dk((rk(h,g,dk(f^c,e^d,f,e)|0,D,0)|0)^a,D^b,a,b)|0}function nk(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;f=i;i=i+16|0;j=f|0;h=b>>31|((b|0)<0?-1:0)<<1;g=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;l=e>>31|((e|0)<0?-1:0)<<1;k=((e|0)<0?-1:0)>>31|((e|0)<0?-1:0)<<1;a=dk(h^a,g^b,h,g)|0;b=D;rk(a,b,dk(l^d,k^e,l,k)|0,D,j)|0;e=dk(c[j>>2]^h,c[j+4>>2]^g,h,g)|0;d=D;i=f;return(D=d,e)|0}function ok(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0;e=a;f=c;c=lk(e,f)|0;a=D;return(D=($(b,f)|0)+($(d,e)|0)+a|a&0,c|0|0)|0}function pk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;return rk(a,b,c,d,0)|0}function qk(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0;g=i;i=i+16|0;f=g|0;rk(a,b,d,e,f)|0;i=g;return(D=c[f+4>>2]|0,c[f>>2]|0)|0}function rk(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;l=a;j=b;k=j;h=d;n=e;i=n;if(!k){g=(f|0)!=0;if(!i){if(g){c[f>>2]=(l>>>0)%(h>>>0);c[f+4>>2]=0}n=0;f=(l>>>0)/(h>>>0)>>>0;return(D=n,f)|0}else{if(!g){n=0;f=0;return(D=n,f)|0}c[f>>2]=a|0;c[f+4>>2]=b&0;n=0;f=0;return(D=n,f)|0}}g=(i|0)==0;do if(h){if(!g){g=(ba(i|0)|0)-(ba(k|0)|0)|0;if(g>>>0<=31){m=g+1|0;i=31-g|0;b=g-31>>31;h=m;a=l>>>(m>>>0)&b|k<<i;b=k>>>(m>>>0)&b;g=0;i=l<<i;break}if(!f){n=0;f=0;return(D=n,f)|0}c[f>>2]=a|0;c[f+4>>2]=j|b&0;n=0;f=0;return(D=n,f)|0}g=h-1|0;if(g&h){i=(ba(h|0)|0)+33-(ba(k|0)|0)|0;p=64-i|0;m=32-i|0;j=m>>31;o=i-32|0;b=o>>31;h=i;a=m-1>>31&k>>>(o>>>0)|(k<<m|l>>>(i>>>0))&b;b=b&k>>>(i>>>0);g=l<<p&j;i=(k<<p|l>>>(o>>>0))&j|l<<m&i-33>>31;break}if(f){c[f>>2]=g&l;c[f+4>>2]=0}if((h|0)==1){o=j|b&0;p=a|0|0;return(D=o,p)|0}else{p=kk(h|0)|0;o=k>>>(p>>>0)|0;p=k<<32-p|l>>>(p>>>0)|0;return(D=o,p)|0}}else{if(g){if(f){c[f>>2]=(k>>>0)%(h>>>0);c[f+4>>2]=0}o=0;p=(k>>>0)/(h>>>0)>>>0;return(D=o,p)|0}if(!l){if(f){c[f>>2]=0;c[f+4>>2]=(k>>>0)%(i>>>0)}o=0;p=(k>>>0)/(i>>>0)>>>0;return(D=o,p)|0}g=i-1|0;if(!(g&i)){if(f){c[f>>2]=a|0;c[f+4>>2]=g&k|b&0}o=0;p=k>>>((kk(i|0)|0)>>>0);return(D=o,p)|0}g=(ba(i|0)|0)-(ba(k|0)|0)|0;if(g>>>0<=30){b=g+1|0;i=31-g|0;h=b;a=k<<i|l>>>(b>>>0);b=k>>>(b>>>0);g=0;i=l<<i;break}if(!f){o=0;p=0;return(D=o,p)|0}c[f>>2]=a|0;c[f+4>>2]=j|b&0;o=0;p=0;return(D=o,p)|0}while(0);if(!h){k=i;j=0;i=0}else{m=d|0|0;l=n|e&0;k=gk(m|0,l|0,-1,-1)|0;d=D;j=i;i=0;do{e=j;j=g>>>31|j<<1;g=i|g<<1;e=a<<1|e>>>31|0;n=a>>>31|b<<1|0;dk(k,d,e,n)|0;p=D;o=p>>31|((p|0)<0?-1:0)<<1;i=o&1;a=dk(e,n,o&m,(((p|0)<0?-1:0)>>31|((p|0)<0?-1:0)<<1)&l)|0;b=D;h=h-1|0}while((h|0)!=0);k=j;j=0}h=0;if(f){c[f>>2]=a;c[f+4>>2]=b}o=(g|0)>>>31|(k|h)<<1|(h<<1|g>>>31)&0|j;p=(g<<1|0>>>31)&-2|i;return(D=o,p)|0}function sk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;return Qb[a&15](b|0,c|0,d|0)|0}function tk(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;Rb[a&3](b|0,c|0,d|0,e|0,f|0)}function uk(a,b,c){a=a|0;b=b|0;c=c|0;return+Sb[a&1](b|0,c|0)}function vk(a,b,c){a=a|0;b=b|0;c=+c;Tb[a&3](b|0,+c)}function wk(a,b){a=a|0;b=b|0;return+Ub[a&3](b|0)}function xk(a){a=a|0;return Vb[a&1]()|0}function yk(a,b){a=a|0;b=b|0;Wb[a&15](b|0)}function zk(a,b,c){a=a|0;b=b|0;c=c|0;Xb[a&7](b|0,c|0)}function Ak(a,b){a=a|0;b=b|0;return Yb[a&31](b|0)|0}function Bk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;Zb[a&1](b|0,c|0,d|0)}function Ck(a){a=a|0;_b[a&0]()}function Dk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=+d;$b[a&3](b|0,c|0,+d)}function Ek(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;return ac[a&1](b|0,c|0,d|0,e|0)|0}function Fk(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;bc[a&3](b|0,c|0,d|0,e|0,f|0,g|0)}function Gk(a,b,c){a=a|0;b=b|0;c=c|0;return cc[a&15](b|0,c|0)|0}function Hk(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;dc[a&3](b|0,c|0,d|0,e|0)}function Ik(a,b,c){a=a|0;b=b|0;c=c|0;ca(0);return 0}function Jk(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;ca(1)}function Kk(a,b){a=a|0;b=b|0;ca(2);return 0.0}function Lk(a,b){a=a|0;b=+b;ca(3)}function Mk(a){a=a|0;ca(4);return 0.0}function Nk(){ca(5);return 0}function Ok(a){a=a|0;ca(6)}function Pk(a,b){a=a|0;b=b|0;ca(7)}function Qk(a){a=a|0;ca(8);return 0}function Rk(a,b,c){a=a|0;b=b|0;c=c|0;ca(9)}function Sk(){ca(10)}function Tk(a,b,c){a=a|0;b=b|0;c=+c;ca(11)}function Uk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;ca(12);return 0}function Vk(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;ca(13)}function Wk(a,b){a=a|0;b=b|0;ca(14);return 0}function Xk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;ca(15)}var Qb=[Ik,Zh,_h,Qj,Qi,Pi,Ri,Ag,sg,qg,rg,yg,kh,jh,Oi,Mj];var Rb=[Jk,ki,ji,gi];var Sb=[Kk,dh];var Tb=[Lk,Wf,Yf,ag];var Ub=[Mk,Xf,Zf,bg];var Vb=[Nk,Nf];var Wb=[Ok,Mh,Nh,Sh,Vh,Th,Uh,Wh,Xh,Yh,Mf,Xg,Yg,Ij,Jj,Ok];var Xb=[Pk,ig,gg,_f,cg,eg,ng,gh];var Yb=[Qk,Oh,Ni,Pf,Vf,Qf,wg,xg,mg,lg,jg,hg,$f,dg,fg,og,fh,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk];var Zb=[Rk,ch];var _b=[Sk];var $b=[Tk,eh,bh,Tk];var ac=[Uk,mh];var bc=[Vk,ni,mi,li];var cc=[Wk,Df,Sf,Tf,Uf,tg,vg,ug,zg,kg,lh,hh,Wk,Wk,Wk,Wk];var dc=[Xk,ai,bi,di];return{_i64Subtract:dk,_fflush:Yi,_i64Add:gk,_memset:ek,_malloc:Uj,_memcpy:ik,___getTypeName:Ah,_bitshift64Lshr:hk,_free:Vj,___errno_location:qi,_bitshift64Shl:fk,__GLOBAL__sub_I_ARToolKitJS_cpp:Wg,__GLOBAL__sub_I_bind_cpp:Ch,runPostSets:ck,stackAlloc:ec,stackSave:fc,stackRestore:gc,establishStackSpace:hc,setThrew:ic,setTempRet0:lc,getTempRet0:mc,dynCall_iiii:sk,dynCall_viiiii:tk,dynCall_dii:uk,dynCall_vid:vk,dynCall_di:wk,dynCall_i:xk,dynCall_vi:yk,dynCall_vii:zk,dynCall_ii:Ak,dynCall_viii:Bk,dynCall_v:Ck,dynCall_viid:Dk,dynCall_iiiii:Ek,dynCall_viiiiii:Fk,dynCall_iii:Gk,dynCall_viiii:Hk}}(Module.asmGlobalArg,Module.asmLibraryArg,buffer);var _i64Subtract=Module["_i64Subtract"]=asm["_i64Subtract"];var __GLOBAL__sub_I_bind_cpp=Module["__GLOBAL__sub_I_bind_cpp"]=asm["__GLOBAL__sub_I_bind_cpp"];var _fflush=Module["_fflush"]=asm["_fflush"];var __GLOBAL__sub_I_ARToolKitJS_cpp=Module["__GLOBAL__sub_I_ARToolKitJS_cpp"]=asm["__GLOBAL__sub_I_ARToolKitJS_cpp"];var _i64Add=Module["_i64Add"]=asm["_i64Add"];var _memset=Module["_memset"]=asm["_memset"];var runPostSets=Module["runPostSets"]=asm["runPostSets"];var _malloc=Module["_malloc"]=asm["_malloc"];var _memcpy=Module["_memcpy"]=asm["_memcpy"];var ___getTypeName=Module["___getTypeName"]=asm["___getTypeName"];var _bitshift64Lshr=Module["_bitshift64Lshr"]=asm["_bitshift64Lshr"];var _free=Module["_free"]=asm["_free"];var ___errno_location=Module["___errno_location"]=asm["___errno_location"];var _bitshift64Shl=Module["_bitshift64Shl"]=asm["_bitshift64Shl"];var dynCall_iiii=Module["dynCall_iiii"]=asm["dynCall_iiii"];var dynCall_viiiii=Module["dynCall_viiiii"]=asm["dynCall_viiiii"];var dynCall_dii=Module["dynCall_dii"]=asm["dynCall_dii"];var dynCall_vid=Module["dynCall_vid"]=asm["dynCall_vid"];var dynCall_di=Module["dynCall_di"]=asm["dynCall_di"];var dynCall_i=Module["dynCall_i"]=asm["dynCall_i"];var dynCall_vi=Module["dynCall_vi"]=asm["dynCall_vi"];var dynCall_vii=Module["dynCall_vii"]=asm["dynCall_vii"];var dynCall_ii=Module["dynCall_ii"]=asm["dynCall_ii"];var dynCall_viii=Module["dynCall_viii"]=asm["dynCall_viii"];var dynCall_v=Module["dynCall_v"]=asm["dynCall_v"];var dynCall_viid=Module["dynCall_viid"]=asm["dynCall_viid"];var dynCall_iiiii=Module["dynCall_iiiii"]=asm["dynCall_iiiii"];var dynCall_viiiiii=Module["dynCall_viiiiii"]=asm["dynCall_viiiiii"];var dynCall_iii=Module["dynCall_iii"]=asm["dynCall_iii"];var dynCall_viiii=Module["dynCall_viiii"]=asm["dynCall_viiii"];Runtime.stackAlloc=asm["stackAlloc"];Runtime.stackSave=asm["stackSave"];Runtime.stackRestore=asm["stackRestore"];Runtime.establishStackSpace=asm["establishStackSpace"];Runtime.setTempRet0=asm["setTempRet0"];Runtime.getTempRet0=asm["getTempRet0"];function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}ExitStatus.prototype=new Error;ExitStatus.prototype.constructor=ExitStatus;var initialStackTop;var preloadStartTime=null;var calledMain=false;dependenciesFulfilled=function runCaller(){if(!Module["calledRun"])run();if(!Module["calledRun"])dependenciesFulfilled=runCaller};Module["callMain"]=Module.callMain=function callMain(args){assert(runDependencies==0,"cannot call main when async dependencies remain! (listen on __ATMAIN__)");assert(__ATPRERUN__.length==0,"cannot call main when preRun functions remain to be called");args=args||[];ensureInitRuntime();var argc=args.length+1;function pad(){for(var i=0;i<4-1;i++){argv.push(0)}}var argv=[allocate(intArrayFromString(Module["thisProgram"]),"i8",ALLOC_NORMAL)];pad();for(var i=0;i<argc-1;i=i+1){argv.push(allocate(intArrayFromString(args[i]),"i8",ALLOC_NORMAL));pad()}argv.push(0);argv=allocate(argv,"i32",ALLOC_NORMAL);try{var ret=Module["_main"](argc,argv,0);exit(ret,true)}catch(e){if(e instanceof ExitStatus){return}else if(e=="SimulateInfiniteLoop"){Module["noExitRuntime"]=true;return}else{if(e&&typeof e==="object"&&e.stack)Module.printErr("exception thrown: "+[e,e.stack]);throw e}}finally{calledMain=true}};function run(args){args=args||Module["arguments"];if(preloadStartTime===null)preloadStartTime=Date.now();if(runDependencies>0){return}preRun();if(runDependencies>0)return;if(Module["calledRun"])return;function doRun(){if(Module["calledRun"])return;Module["calledRun"]=true;if(ABORT)return;ensureInitRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(Module["_main"]&&shouldRunNow)Module["callMain"](args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=Module.run=run;function exit(status,implicit){if(implicit&&Module["noExitRuntime"]){return}if(Module["noExitRuntime"]){}else{ABORT=true;EXITSTATUS=status;STACKTOP=initialStackTop;exitRuntime();if(Module["onExit"])Module["onExit"](status)}if(ENVIRONMENT_IS_NODE){process["stdout"]["once"]("drain",function(){process["exit"](status)});console.log(" ");setTimeout(function(){process["exit"](status)},500)}else if(ENVIRONMENT_IS_SHELL&&typeof quit==="function"){quit(status)}throw new ExitStatus(status)}Module["exit"]=Module.exit=exit;var abortDecorators=[];function abort(what){if(what!==undefined){Module.print(what);Module.printErr(what);what=JSON.stringify(what)}else{what=""}ABORT=true;EXITSTATUS=1;var extra="\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.";var output="abort("+what+") at "+stackTrace()+extra;if(abortDecorators){abortDecorators.forEach(function(decorator){output=decorator(output,what)})}throw output}Module["abort"]=Module.abort=abort;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=true;if(Module["noInitialRun"]){shouldRunNow=false}run();(function(){"use strict";var ARController=function(width,height,camera){var id;var w=width,h=height;this.orientation="landscape";this.listeners={};if(typeof width!=="number"){var image=width;camera=height;w=image.videoWidth||image.width;h=image.videoHeight||image.height;this.image=image}this.defaultMarkerWidth=1;this.patternMarkers={};this.barcodeMarkers={};this.transform_mat=new Float32Array(16);this.canvas=document.createElement("canvas");this.canvas.width=w;this.canvas.height=h;this.ctx=this.canvas.getContext("2d");this.videoWidth=w;this.videoHeight=h;if(typeof camera==="string"){var self=this;this.cameraParam=new ARCameraParam(camera,function(){self._initialize()},function(err){console.error("ARController: Failed to load ARCameraParam",err)})}else{this.cameraParam=camera;this._initialize()}};ARController.prototype.dispose=function(){artoolkit.teardown(this.id);for(var t in this){this[t]=null}};ARController.prototype.process=function(image){this.detectMarker(image);var markerNum=this.getMarkerNum();var k,o;for(k in this.patternMarkers){o=this.patternMarkers[k];o.inPrevious=o.inCurrent;o.inCurrent=false}for(k in this.barcodeMarkers){o=this.barcodeMarkers[k];o.inPrevious=o.inCurrent;o.inCurrent=false}for(var i=0;i<markerNum;i++){var markerInfo=this.getMarker(i);var markerType=artoolkit.UNKNOWN_MARKER;var visible=this.trackPatternMarkerId(-1);if(markerInfo.idPatt>-1&&(markerInfo.id===markerInfo.idPatt||markerInfo.idMatrix===-1)){visible=this.trackPatternMarkerId(markerInfo.idPatt);markerType=artoolkit.PATTERN_MARKER;if(markerInfo.dir!==markerInfo.dirPatt){this.setMarkerInfoDir(i,markerInfo.dirPatt)}}else if(markerInfo.idMatrix>-1){visible=this.trackBarcodeMarkerId(markerInfo.idMatrix);markerType=artoolkit.BARCODE_MARKER;if(markerInfo.dir!==markerInfo.dirMatrix){this.setMarkerInfoDir(i,markerInfo.dirMatrix)}}if(markerType!==artoolkit.UNKNOWN_MARKER&&visible.inPrevious){this.getTransMatSquareCont(i,visible.markerWidth,visible.matrix,visible.matrix)}else{this.getTransMatSquare(i,visible.markerWidth,visible.matrix)}visible.inCurrent=true;this.transMatToGLMat(visible.matrix,this.transform_mat);this.dispatchEvent({name:"getMarker",target:this,data:{index:i,type:markerType,marker:markerInfo,matrix:this.transform_mat}})}var multiMarkerCount=this.getMultiMarkerCount();for(var i=0;i<multiMarkerCount;i++){var subMarkerCount=this.getMultiMarkerPatternCount(i);var visible=false;artoolkit.getTransMatMultiSquareRobust(this.id,i);this.transMatToGLMat(this.marker_transform_mat,this.transform_mat);for(var j=0;j<subMarkerCount;j++){var multiEachMarkerInfo=this.getMultiEachMarker(i,j);if(multiEachMarkerInfo.visible>=0){visible=true;this.dispatchEvent({name:"getMultiMarker",target:this,data:{multiMarkerId:i,matrix:this.transform_mat}});break}}if(visible){for(var j=0;j<subMarkerCount;j++){var multiEachMarkerInfo=this.getMultiEachMarker(i,j);this.transMatToGLMat(this.marker_transform_mat,this.transform_mat);this.dispatchEvent({name:"getMultiMarkerSub",target:this,data:{multiMarkerId:i,markerIndex:j,marker:multiEachMarkerInfo,matrix:this.transform_mat}})}}}if(this._bwpointer){this.debugDraw()}};ARController.prototype.trackPatternMarkerId=function(id,markerWidth){var obj=this.patternMarkers[id];if(!obj){this.patternMarkers[id]=obj={inPrevious:false,inCurrent:false,matrix:new Float32Array(12),markerWidth:markerWidth||this.defaultMarkerWidth}}if(markerWidth){obj.markerWidth=markerWidth}return obj};ARController.prototype.trackBarcodeMarkerId=function(id,markerWidth){var obj=this.barcodeMarkers[id];if(!obj){this.barcodeMarkers[id]=obj={inPrevious:false,inCurrent:false,matrix:new Float32Array(12),markerWidth:markerWidth||this.defaultMarkerWidth}}if(markerWidth){obj.markerWidth=markerWidth}return obj};ARController.prototype.getMultiMarkerCount=function(){return artoolkit.getMultiMarkerCount(this.id)};ARController.prototype.getMultiMarkerPatternCount=function(multiMarkerId){return artoolkit.getMultiMarkerNum(this.id,multiMarkerId)};ARController.prototype.addEventListener=function(name,callback){if(!this.listeners[name]){this.listeners[name]=[]}this.listeners[name].push(callback)};ARController.prototype.removeEventListener=function(name,callback){if(this.listeners[name]){var index=this.listeners[name].indexOf(callback);if(index>-1){this.listeners[name].splice(index,1)}}};ARController.prototype.dispatchEvent=function(event){var listeners=this.listeners[event.name];if(listeners){for(var i=0;i<listeners.length;i++){listeners[i].call(this,event)}}};ARController.prototype.debugSetup=function(){document.body.appendChild(this.canvas);this.setDebugMode(1);this._bwpointer=this.getProcessingImage()};ARController.prototype.loadMarker=function(markerURL,onSuccess,onError){return artoolkit.addMarker(this.id,markerURL,onSuccess,onError)};ARController.prototype.loadMultiMarker=function(markerURL,onSuccess,onError){return artoolkit.addMultiMarker(this.id,markerURL,onSuccess,onError)};ARController.prototype.getTransMatSquare=function(markerIndex,markerWidth,dst){artoolkit.getTransMatSquare(this.id,markerIndex,markerWidth);dst.set(this.marker_transform_mat);return dst};ARController.prototype.getTransMatSquareCont=function(markerIndex,markerWidth,previousMarkerTransform,dst){this.marker_transform_mat.set(previousMarkerTransform);artoolkit.getTransMatSquareCont(this.id,markerIndex,markerWidth);dst.set(this.marker_transform_mat);return dst};ARController.prototype.getTransMatMultiSquare=function(multiMarkerId,dst){artoolkit.getTransMatMultiSquare(this.id,multiMarkerId);dst.set(this.marker_transform_mat);return dst};ARController.prototype.getTransMatMultiSquareRobust=function(multiMarkerId,dst){artoolkit.getTransMatMultiSquare(this.id,multiMarkerId);dst.set(this.marker_transform_mat);return dst};ARController.prototype.transMatToGLMat=function(transMat,glMat,scale){glMat[0+0*4]=transMat[0];glMat[0+1*4]=transMat[1];glMat[0+2*4]=transMat[2];glMat[0+3*4]=transMat[3];glMat[1+0*4]=transMat[4];glMat[1+1*4]=transMat[5];glMat[1+2*4]=transMat[6];glMat[1+3*4]=transMat[7];glMat[2+0*4]=transMat[8];glMat[2+1*4]=transMat[9];glMat[2+2*4]=transMat[10];glMat[2+3*4]=transMat[11];glMat[3+0*4]=0;glMat[3+1*4]=0;glMat[3+2*4]=0;glMat[3+3*4]=1;if(scale!=undefined&&scale!==0){glMat[12]*=scale;glMat[13]*=scale;glMat[14]*=scale}return glMat};ARController.prototype.detectMarker=function(image){if(this._copyImageToHeap(image)){return artoolkit.detectMarker(this.id)}return-99};ARController.prototype.getMarkerNum=function(){return artoolkit.getMarkerNum(this.id)};ARController.prototype.getMarker=function(markerIndex){if(0===artoolkit.getMarker(this.id,markerIndex)){return artoolkit.markerInfo}};ARController.prototype.setMarkerInfoVertex=function(markerIndex,vertexData){for(var i=0;i<vertexData.length;i++){this.marker_transform_mat[i*2+0]=vertexData[i][0];this.marker_transform_mat[i*2+1]=vertexData[i][1]}return artoolkit.setMarkerInfoVertex(this.id,markerIndex)};ARController.prototype.cloneMarkerInfo=function(markerInfo){return JSON.parse(JSON.stringify(markerInfo))};ARController.prototype.getMultiEachMarker=function(multiMarkerId,markerIndex){if(0===artoolkit.getMultiEachMarker(this.id,multiMarkerId,markerIndex)){return artoolkit.multiEachMarkerInfo}};ARController.prototype.getTransformationMatrix=function(){return this.transform_mat};ARController.prototype.getCameraMatrix=function(){return this.camera_mat};ARController.prototype.getMarkerTransformationMatrix=function(){return this.marker_transform_mat};ARController.prototype.setDebugMode=function(mode){return artoolkit.setDebugMode(this.id,mode)};ARController.prototype.getDebugMode=function(){return artoolkit.getDebugMode(this.id)};ARController.prototype.getProcessingImage=function(){return artoolkit.getProcessingImage(this.id)};ARController.prototype.setLogLevel=function(mode){return artoolkit.setLogLevel(mode)};ARController.prototype.getLogLevel=function(){return artoolkit.getLogLevel()};ARController.prototype.setMarkerInfoDir=function(markerIndex,dir){return artoolkit.setMarkerInfoDir(this.id,markerIndex,dir)};ARController.prototype.setProjectionNearPlane=function(value){return artoolkit.setProjectionNearPlane(this.id,value)};ARController.prototype.getProjectionNearPlane=function(){return artoolkit.getProjectionNearPlane(this.id)};ARController.prototype.setProjectionFarPlane=function(value){return artoolkit.setProjectionFarPlane(this.id,value)};ARController.prototype.getProjectionFarPlane=function(){return artoolkit.getProjectionFarPlane(this.id)};ARController.prototype.setThresholdMode=function(mode){return artoolkit.setThresholdMode(this.id,mode)};ARController.prototype.getThresholdMode=function(){return artoolkit.getThresholdMode(this.id)};ARController.prototype.setThreshold=function(threshold){return artoolkit.setThreshold(this.id,threshold)};ARController.prototype.getThreshold=function(){return artoolkit.getThreshold(this.id)};ARController.prototype.setPatternDetectionMode=function(value){return artoolkit.setPatternDetectionMode(this.id,value)};ARController.prototype.getPatternDetectionMode=function(){return artoolkit.getPatternDetectionMode(this.id)};ARController.prototype.setMatrixCodeType=function(value){return artoolkit.setMatrixCodeType(this.id,value)};ARController.prototype.getMatrixCodeType=function(){return artoolkit.getMatrixCodeType(this.id)};ARController.prototype.setLabelingMode=function(value){return artoolkit.setLabelingMode(this.id,value)};ARController.prototype.getLabelingMode=function(){return artoolkit.getLabelingMode(this.id)};ARController.prototype.setPattRatio=function(value){return artoolkit.setPattRatio(this.id,value)};ARController.prototype.getPattRatio=function(){return artoolkit.getPattRatio(this.id)};ARController.prototype.setImageProcMode=function(value){return artoolkit.setImageProcMode(this.id,value)};ARController.prototype.getImageProcMode=function(){return artoolkit.getImageProcMode(this.id)};ARController.prototype.debugDraw=function(){var debugBuffer=new Uint8ClampedArray(Module.HEAPU8.buffer,this._bwpointer,this.framesize);var id=new ImageData(debugBuffer,this.canvas.width,this.canvas.height);this.ctx.putImageData(id,0,0);var marker_num=this.getMarkerNum();for(var i=0;i<marker_num;i++){this._debugMarker(this.getMarker(i))}};ARController.prototype._initialize=function(){this.id=artoolkit.setup(this.canvas.width,this.canvas.height,this.cameraParam.id);var params=artoolkit.frameMalloc;this.framepointer=params.framepointer;this.framesize=params.framesize;this.dataHeap=new Uint8Array(Module.HEAPU8.buffer,this.framepointer,this.framesize);this.camera_mat=new Float64Array(Module.HEAPU8.buffer,params.camera,16);this.marker_transform_mat=new Float64Array(Module.HEAPU8.buffer,params.transform,12);this.setProjectionNearPlane(.1);this.setProjectionFarPlane(1e3);var self=this;setTimeout(function(){if(self.onload){self.onload()}self.dispatchEvent({name:"load",target:self})},1)};ARController.prototype._copyImageToHeap=function(image){if(!image){image=this.image}if(image.nodeName==="IMG"&&image.width>image.height||image.nodeName==="VIDEO"&&image.videoWidth>image.videoHeight){this.ctx.drawImage(image,0,0,this.canvas.width,this.canvas.height)}else{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);var scale=this.canvas.height/this.canvas.width;var scaledHeight=this.canvas.width*scale;var scaledWidth=this.canvas.height*scale;var marginLeft=(this.canvas.width-scaledWidth)/2;this.ctx.drawImage(image,marginLeft,0,scaledWidth,scaledHeight)}var imageData=this.ctx.getImageData(0,0,this.canvas.width,this.canvas.height);var data=imageData.data;if(this.dataHeap){this.dataHeap.set(data);return true}return false};ARController.prototype._debugMarker=function(marker){var vertex,pos;vertex=marker.vertex;var ctx=this.ctx;ctx.strokeStyle="red";ctx.beginPath();ctx.moveTo(vertex[0][0],vertex[0][1]);ctx.lineTo(vertex[1][0],vertex[1][1]);ctx.stroke();ctx.beginPath();ctx.moveTo(vertex[2][0],vertex[2][1]);ctx.lineTo(vertex[3][0],vertex[3][1]);ctx.stroke();ctx.strokeStyle="green";ctx.beginPath();ctx.lineTo(vertex[1][0],vertex[1][1]);ctx.lineTo(vertex[2][0],vertex[2][1]);ctx.stroke();ctx.beginPath();ctx.moveTo(vertex[3][0],vertex[3][1]);ctx.lineTo(vertex[0][0],vertex[0][1]);ctx.stroke();pos=marker.pos;ctx.beginPath();ctx.arc(pos[0],pos[1],8,0,Math.PI*2);ctx.fillStyle="red";ctx.fill()};ARController.getUserMedia=function(configuration){var facing=configuration.facingMode||"environment";var onSuccess=configuration.onSuccess;var onError=configuration.onError||function(err){console.error("ARController.getUserMedia",err)};var video=document.createElement("video");var initProgress=function(){if(this.videoWidth!==0){onSuccess(video)}};var readyToPlay=false;var eventNames=["touchstart","touchend","touchmove","touchcancel","click","mousedown","mouseup","mousemove","keydown","keyup","keypress","scroll"];var play=function(ev){if(readyToPlay){video.play();if(!video.paused){eventNames.forEach(function(eventName){window.removeEventListener(eventName,play,true)})}}};eventNames.forEach(function(eventName){window.addEventListener(eventName,play,true);
});var success=function(stream){video.addEventListener("loadedmetadata",initProgress,false);video.src=window.URL.createObjectURL(stream);readyToPlay=true;play()};var constraints={};var mediaDevicesConstraints={};if(configuration.width){mediaDevicesConstraints.width=configuration.width;if(typeof configuration.width==="object"){if(configuration.width.max){constraints.maxWidth=configuration.width.max}if(configuration.width.min){constraints.minWidth=configuration.width.max}}else{constraints.maxWidth=configuration.width}}if(configuration.height){mediaDevicesConstraints.height=configuration.height;if(typeof configuration.height==="object"){if(configuration.height.max){constraints.maxHeight=configuration.height.max}if(configuration.height.min){constraints.minHeight=configuration.height.max}}else{constraints.maxHeight=configuration.height}}mediaDevicesConstraints.facingMode=facing;navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var hdConstraints={audio:false,video:{mandatory:constraints}};if(false){if(navigator.mediaDevices){navigator.mediaDevices.getUserMedia({audio:false,video:mediaDevicesConstraints}).then(success,onError)}else{MediaStreamTrack.getSources(function(sources){var facingDir=mediaDevicesConstraints.facingMode;if(facing&&facing.exact){facingDir=facing.exact}for(var i=0;i<sources.length;i++){if(sources[i].kind==="video"&&sources[i].facing===facingDir){hdConstraints.video.mandatory.sourceId=sources[i].id;break}}if(facing&&facing.exact&&!hdConstraints.video.mandatory.sourceId){onError("Failed to get camera facing the wanted direction")}else{if(navigator.getUserMedia){navigator.getUserMedia(hdConstraints,success,onError)}else{onError("navigator.getUserMedia is not supported on your browser")}}})}}else{if(navigator.getUserMedia){navigator.getUserMedia(hdConstraints,success,onError)}else{onError("navigator.getUserMedia is not supported on your browser")}}return video};ARController.getUserMediaARController=function(configuration){var obj={};for(var i in configuration){obj[i]=configuration[i]}var onSuccess=configuration.onSuccess;var cameraParamURL=configuration.cameraParam;obj.onSuccess=function(){new ARCameraParam(cameraParamURL,function(){var arCameraParam=this;var maxSize=configuration.maxARVideoSize||Math.max(video.videoWidth,video.videoHeight);var f=maxSize/Math.max(video.videoWidth,video.videoHeight);var w=f*video.videoWidth;var h=f*video.videoHeight;if(video.videoWidth<video.videoHeight){var tmp=w;w=h;h=tmp}var arController=new ARController(w,h,arCameraParam);arController.image=video;if(video.videoWidth<video.videoHeight){arController.orientation="portrait";arController.videoWidth=video.videoHeight;arController.videoHeight=video.videoWidth}else{arController.orientation="landscape";arController.videoWidth=video.videoWidth;arController.videoHeight=video.videoHeight}onSuccess(arController,arCameraParam)},function(err){console.error("ARController: Failed to load ARCameraParam",err)})};var video=this.getUserMedia(obj);return video};var ARCameraParam=function(src,onload,onerror){this.id=-1;this._src="";this.complete=false;this.onload=onload;this.onerror=onerror;if(src){this.load(src)}};ARCameraParam.prototype.load=function(src){if(this._src!==""){throw"ARCameraParam: Trying to load camera parameters twice."}this._src=src;if(src){var self=this;artoolkit.loadCamera(src,function(id){self.id=id;self.complete=true;self.onload()},function(err){self.onerror(err)})}};Object.defineProperty(ARCameraParam.prototype,"src",{set:function(src){this.load(src)},get:function(){return this._src}});ARCameraParam.prototype.dispose=function(){if(this.id!==-1){artoolkit.deleteCamera(this.id)}this.id=-1;this._src="";this.complete=false};var artoolkit={UNKNOWN_MARKER:-1,PATTERN_MARKER:0,BARCODE_MARKER:1,loadCamera:loadCamera,addMarker:addMarker,addMultiMarker:addMultiMarker};var FUNCTIONS=["setup","teardown","setLogLevel","getLogLevel","setDebugMode","getDebugMode","getProcessingImage","setMarkerInfoDir","setMarkerInfoVertex","getTransMatSquare","getTransMatSquareCont","getTransMatMultiSquare","getTransMatMultiSquareRobust","getMultiMarkerNum","getMultiMarkerCount","detectMarker","getMarkerNum","getMarker","getMultiEachMarker","setProjectionNearPlane","getProjectionNearPlane","setProjectionFarPlane","getProjectionFarPlane","setThresholdMode","getThresholdMode","setThreshold","getThreshold","setPatternDetectionMode","getPatternDetectionMode","setMatrixCodeType","getMatrixCodeType","setLabelingMode","getLabelingMode","setPattRatio","getPattRatio","setImageProcMode","getImageProcMode"];function runWhenLoaded(){FUNCTIONS.forEach(function(n){artoolkit[n]=Module[n]});for(var m in Module){if(m.match(/^AR/))artoolkit[m]=Module[m]}}var marker_count=0;function addMarker(arId,url,callback){var filename="/marker_"+marker_count++;ajax(url,filename,function(){var id=Module._addMarker(arId,filename);if(callback)callback(id)})}function bytesToString(array){return String.fromCharCode.apply(String,array)}function parseMultiFile(bytes){var str=bytesToString(bytes);var lines=str.split("\n");var files=[];var state=0;var markers=0;lines.forEach(function(line){line=line.trim();if(!line||line.startsWith("#"))return;switch(state){case 0:markers=+line;state=1;return;case 1:if(!line.match(/^\d+$/)){files.push(line)}case 2:case 3:case 4:state++;return;case 5:state=1;return}});return files}var multi_marker_count=0;function addMultiMarker(arId,url,callback){var filename="/multi_marker_"+multi_marker_count++;ajax(url,filename,function(bytes){var files=parseMultiFile(bytes);function ok(){var markerID=Module._addMultiMarker(arId,filename);var markerNum=Module.getMultiMarkerNum(arId,markerID);if(callback)callback(markerID,markerNum)}if(!files.length)return ok();var path=url.split("/").slice(0,-1).join("/");files=files.map(function(file){if(file==="patt.hiro"||file==="patt.kanji"||file==="patt2.hiro"||file==="patt2.kanji"){return["http://127.0.0.1:8080/data/data/"+file,file]}return[path+"/"+file,file]});ajaxDependencies(files,ok)})}var camera_count=0;function loadCamera(url,callback){var filename="/camera_param_"+camera_count++;var writeCallback=function(){var id=Module._loadCamera(filename);if(callback)callback(id)};if(typeof url==="object"){writeByteArrayToFS(filename,url,writeCallback)}else if(url.indexOf("\n")>-1){writeStringToFS(filename,url,writeCallback)}else{ajax(url,filename,writeCallback)}}function writeStringToFS(target,string,callback){var byteArray=new Uint8Array(string.length);for(var i=0;i<byteArray.length;i++){byteArray[i]=string.charCodeAt(i)&255}writeByteArrayToFS(target,byteArray,callback)}function writeByteArrayToFS(target,byteArray,callback){FS.writeFile(target,byteArray,{encoding:"binary"});callback(byteArray)}function ajax(url,target,callback){var oReq=new XMLHttpRequest;oReq.open("GET",url,true);oReq.responseType="arraybuffer";oReq.onload=function(oEvent){var arrayBuffer=oReq.response;var byteArray=new Uint8Array(arrayBuffer);writeByteArrayToFS(target,byteArray,callback)};oReq.send()}function ajaxDependencies(files,callback){var next=files.pop();if(next){ajax(next[0],next[1],function(){ajaxDependencies(files,callback)})}else{callback()}}window.artoolkit=artoolkit;window.ARController=ARController;window.ARCameraParam=ARCameraParam;if(window.Module){runWhenLoaded()}else{window.Module={onRuntimeInitialized:function(){runWhenLoaded()}}}})();var AR=AR||{};AR.Marker=function(id,corners){this.id=id;this.corners=corners};AR.Detector=function(){this.grey=new CV.Image;this.thres=new CV.Image;this.homography=new CV.Image;this.binary=[];this.contours=[];this.polys=[];this.candidates=[]};AR.Detector.prototype.detect=function(image){CV.grayscale(image,this.grey);CV.adaptiveThreshold(this.grey,this.thres,2,7);this.contours=CV.findContours(this.thres,this.binary);this.candidates=this.findCandidates(this.contours,image.width*.2,.05,10);this.candidates=this.clockwiseCorners(this.candidates);this.candidates=this.notTooNear(this.candidates,10);return this.findMarkers(this.grey,this.candidates,49)};AR.Detector.prototype.findCandidates=function(contours,minSize,epsilon,minLength){var candidates=[],len=contours.length,contour,poly,i;this.polys=[];for(i=0;i<len;++i){contour=contours[i];if(contour.length>=minSize){poly=CV.approxPolyDP(contour,contour.length*epsilon);this.polys.push(poly);if(4===poly.length&&CV.isContourConvex(poly)){if(CV.minEdgeLength(poly)>=minLength){candidates.push(poly)}}}}return candidates};AR.Detector.prototype.clockwiseCorners=function(candidates){var len=candidates.length,dx1,dx2,dy1,dy2,swap,i;for(i=0;i<len;++i){dx1=candidates[i][1].x-candidates[i][0].x;dy1=candidates[i][1].y-candidates[i][0].y;dx2=candidates[i][2].x-candidates[i][0].x;dy2=candidates[i][2].y-candidates[i][0].y;if(dx1*dy2-dy1*dx2<0){swap=candidates[i][1];candidates[i][1]=candidates[i][3];candidates[i][3]=swap}}return candidates};AR.Detector.prototype.notTooNear=function(candidates,minDist){var notTooNear=[],len=candidates.length,dist,dx,dy,i,j,k;for(i=0;i<len;++i){for(j=i+1;j<len;++j){dist=0;for(k=0;k<4;++k){dx=candidates[i][k].x-candidates[j][k].x;dy=candidates[i][k].y-candidates[j][k].y;dist+=dx*dx+dy*dy}if(dist/4<minDist*minDist){if(CV.perimeter(candidates[i])<CV.perimeter(candidates[j])){candidates[i].tooNear=true}else{candidates[j].tooNear=true}}}}for(i=0;i<len;++i){if(!candidates[i].tooNear){notTooNear.push(candidates[i])}}return notTooNear};AR.Detector.prototype.findMarkers=function(imageSrc,candidates,warpSize){var markers=[],len=candidates.length,candidate,marker,i;for(i=0;i<len;++i){candidate=candidates[i];CV.warp(imageSrc,this.homography,candidate,warpSize);CV.threshold(this.homography,this.homography,CV.otsu(this.homography));marker=this.getMarker(this.homography,candidate);if(marker){markers.push(marker)}}return markers};AR.Detector.prototype.getMarker=function(imageSrc,candidate){var width=imageSrc.width/7>>>0,minZero=width*width>>1,bits=[],rotations=[],distances=[],square,pair,inc,i,j;for(i=0;i<7;++i){inc=0===i||6===i?1:6;for(j=0;j<7;j+=inc){square={x:j*width,y:i*width,width:width,height:width};if(CV.countNonZero(imageSrc,square)>minZero){return null}}}for(i=0;i<5;++i){bits[i]=[];for(j=0;j<5;++j){square={x:(j+1)*width,y:(i+1)*width,width:width,height:width};bits[i][j]=CV.countNonZero(imageSrc,square)>minZero?1:0}}rotations[0]=bits;distances[0]=this.hammingDistance(rotations[0]);pair={first:distances[0],second:0};for(i=1;i<4;++i){rotations[i]=this.rotate(rotations[i-1]);distances[i]=this.hammingDistance(rotations[i]);if(distances[i]<pair.first){pair.first=distances[i];pair.second=i}}if(0!==pair.first){return null}return new AR.Marker(this.mat2id(rotations[pair.second]),this.rotate2(candidate,4-pair.second))};AR.Detector.prototype.hammingDistance=function(bits){var ids=[[1,0,0,0,0],[1,0,1,1,1],[0,1,0,0,1],[0,1,1,1,0]],dist=0,sum,minSum,i,j,k;for(i=0;i<5;++i){minSum=Infinity;for(j=0;j<4;++j){sum=0;for(k=0;k<5;++k){sum+=bits[i][k]===ids[j][k]?0:1}if(sum<minSum){minSum=sum}}dist+=minSum}return dist};AR.Detector.prototype.mat2id=function(bits){var id=0,i;for(i=0;i<5;++i){id<<=1;id|=bits[i][1];id<<=1;id|=bits[i][3]}return id};AR.Detector.prototype.rotate=function(src){var dst=[],len=src.length,i,j;for(i=0;i<len;++i){dst[i]=[];for(j=0;j<src[i].length;++j){dst[i][j]=src[src[i].length-j-1][i]}}return dst};AR.Detector.prototype.rotate2=function(src,rotation){var dst=[],len=src.length,i;for(i=0;i<len;++i){dst[i]=src[(rotation+i)%len]}return dst};var CV=CV||{};CV.Image=function(width,height,data){this.width=width||0;this.height=height||0;this.data=data||[]};CV.grayscale=function(imageSrc,imageDst){var src=imageSrc.data,dst=imageDst.data,len=src.length,i=0,j=0;for(;i<len;i+=4){dst[j++]=src[i]*.299+src[i+1]*.587+src[i+2]*.114+.5&255}imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;return imageDst};CV.threshold=function(imageSrc,imageDst,threshold){var src=imageSrc.data,dst=imageDst.data,len=src.length,tab=[],i;for(i=0;i<256;++i){tab[i]=i<=threshold?0:255}for(i=0;i<len;++i){dst[i]=tab[src[i]]}imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;return imageDst};CV.adaptiveThreshold=function(imageSrc,imageDst,kernelSize,threshold){var src=imageSrc.data,dst=imageDst.data,len=src.length,tab=[],i;CV.stackBoxBlur(imageSrc,imageDst,kernelSize);for(i=0;i<768;++i){tab[i]=i-255<=-threshold?255:0}for(i=0;i<len;++i){dst[i]=tab[src[i]-dst[i]+255]}imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;return imageDst};CV.otsu=function(imageSrc){var src=imageSrc.data,len=src.length,hist=[],threshold=0,sum=0,sumB=0,wB=0,wF=0,max=0,mu,between,i;for(i=0;i<256;++i){hist[i]=0}for(i=0;i<len;++i){hist[src[i]]++}for(i=0;i<256;++i){sum+=hist[i]*i}for(i=0;i<256;++i){wB+=hist[i];if(0!==wB){wF=len-wB;if(0===wF){break}sumB+=hist[i]*i;mu=sumB/wB-(sum-sumB)/wF;between=wB*wF*mu*mu;if(between>max){max=between;threshold=i}}}return threshold};CV.stackBoxBlurMult=[1,171,205,293,57,373,79,137,241,27,391,357,41,19,283,265];CV.stackBoxBlurShift=[0,9,10,11,9,12,10,11,12,9,13,13,10,9,13,13];CV.BlurStack=function(){this.color=0;this.next=null};CV.stackBoxBlur=function(imageSrc,imageDst,kernelSize){var src=imageSrc.data,dst=imageDst.data,height=imageSrc.height,width=imageSrc.width,heightMinus1=height-1,widthMinus1=width-1,size=kernelSize+kernelSize+1,radius=kernelSize+1,mult=CV.stackBoxBlurMult[kernelSize],shift=CV.stackBoxBlurShift[kernelSize],stack,stackStart,color,sum,pos,start,p,x,y,i;stack=stackStart=new CV.BlurStack;for(i=1;i<size;++i){stack=stack.next=new CV.BlurStack}stack.next=stackStart;pos=0;for(y=0;y<height;++y){start=pos;color=src[pos];sum=radius*color;stack=stackStart;for(i=0;i<radius;++i){stack.color=color;stack=stack.next}for(i=1;i<radius;++i){stack.color=src[pos+i];sum+=stack.color;stack=stack.next}stack=stackStart;for(x=0;x<width;++x){dst[pos++]=sum*mult>>>shift;p=x+radius;p=start+(p<widthMinus1?p:widthMinus1);sum-=stack.color-src[p];stack.color=src[p];stack=stack.next}}for(x=0;x<width;++x){pos=x;start=pos+width;color=dst[pos];sum=radius*color;stack=stackStart;for(i=0;i<radius;++i){stack.color=color;stack=stack.next}for(i=1;i<radius;++i){stack.color=dst[start];sum+=stack.color;stack=stack.next;start+=width}stack=stackStart;for(y=0;y<height;++y){dst[pos]=sum*mult>>>shift;p=y+radius;p=x+(p<heightMinus1?p:heightMinus1)*width;sum-=stack.color-dst[p];stack.color=dst[p];stack=stack.next;pos+=width}}return imageDst};CV.gaussianBlur=function(imageSrc,imageDst,imageMean,kernelSize){var kernel=CV.gaussianKernel(kernelSize);imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;imageMean.width=imageSrc.width;imageMean.height=imageSrc.height;CV.gaussianBlurFilter(imageSrc,imageMean,kernel,true);CV.gaussianBlurFilter(imageMean,imageDst,kernel,false);return imageDst};CV.gaussianBlurFilter=function(imageSrc,imageDst,kernel,horizontal){var src=imageSrc.data,dst=imageDst.data,height=imageSrc.height,width=imageSrc.width,pos=0,limit=kernel.length>>1,cur,value,i,j,k;for(i=0;i<height;++i){for(j=0;j<width;++j){value=0;for(k=-limit;k<=limit;++k){if(horizontal){cur=pos+k;if(j+k<0){cur=pos}else if(j+k>=width){cur=pos}}else{cur=pos+k*width;if(i+k<0){cur=pos}else if(i+k>=height){cur=pos}}value+=kernel[limit+k]*src[cur]}dst[pos++]=horizontal?value:value+.5&255}}return imageDst};CV.gaussianKernel=function(kernelSize){var tab=[[1],[.25,.5,.25],[.0625,.25,.375,.25,.0625],[.03125,.109375,.21875,.28125,.21875,.109375,.03125]],kernel=[],center,sigma,scale2X,sum,x,i;if(kernelSize<=7&&kernelSize%2===1){kernel=tab[kernelSize>>1]}else{center=(kernelSize-1)*.5;sigma=.8+.3*(center-1);scale2X=-.5/(sigma*sigma);sum=0;for(i=0;i<kernelSize;++i){x=i-center;sum+=kernel[i]=Math.exp(scale2X*x*x)}sum=1/sum;for(i=0;i<kernelSize;++i){kernel[i]*=sum}}return kernel};CV.findContours=function(imageSrc,binary){var width=imageSrc.width,height=imageSrc.height,contours=[],src,deltas,pos,pix,nbd,outer,hole,i,j;src=CV.binaryBorder(imageSrc,binary);deltas=CV.neighborhoodDeltas(width+2);pos=width+3;nbd=1;for(i=0;i<height;++i,pos+=2){for(j=0;j<width;++j,++pos){pix=src[pos];if(0!==pix){outer=hole=false;if(1===pix&&0===src[pos-1]){outer=true}else if(pix>=1&&0===src[pos+1]){hole=true}if(outer||hole){++nbd;contours.push(CV.borderFollowing(src,pos,nbd,{x:j,y:i},hole,deltas))}}}}return contours};CV.borderFollowing=function(src,pos,nbd,point,hole,deltas){var contour=[],pos1,pos3,pos4,s,s_end,s_prev;contour.hole=hole;s=s_end=hole?0:4;do{s=s-1&7;pos1=pos+deltas[s];if(src[pos1]!==0){break}}while(s!==s_end);if(s===s_end){src[pos]=-nbd;contour.push({x:point.x,y:point.y})}else{pos3=pos;s_prev=s^4;while(true){s_end=s;do{pos4=pos3+deltas[++s]}while(src[pos4]===0);s&=7;if(s-1>>>0<s_end>>>0){src[pos3]=-nbd}else if(src[pos3]===1){src[pos3]=nbd}contour.push({x:point.x,y:point.y});s_prev=s;point.x+=CV.neighborhood[s][0];point.y+=CV.neighborhood[s][1];if(pos4===pos&&pos3===pos1){break}pos3=pos4;s=s+4&7}}return contour};CV.neighborhood=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1]];CV.neighborhoodDeltas=function(width){var deltas=[],len=CV.neighborhood.length,i=0;for(;i<len;++i){deltas[i]=CV.neighborhood[i][0]+CV.neighborhood[i][1]*width}return deltas.concat(deltas)};CV.approxPolyDP=function(contour,epsilon){var slice={start_index:0,end_index:0},right_slice={start_index:0,end_index:0},poly=[],stack=[],len=contour.length,pt,start_pt,end_pt,dist,max_dist,le_eps,dx,dy,i,j,k;epsilon*=epsilon;k=0;for(i=0;i<3;++i){max_dist=0;k=(k+right_slice.start_index)%len;start_pt=contour[k];if(++k===len){k=0}for(j=1;j<len;++j){pt=contour[k];if(++k===len){k=0}dx=pt.x-start_pt.x;dy=pt.y-start_pt.y;dist=dx*dx+dy*dy;if(dist>max_dist){max_dist=dist;right_slice.start_index=j}}}if(max_dist<=epsilon){poly.push({x:start_pt.x,y:start_pt.y})}else{slice.start_index=k;slice.end_index=right_slice.start_index+=slice.start_index;right_slice.start_index-=right_slice.start_index>=len?len:0;right_slice.end_index=slice.start_index;if(right_slice.end_index<right_slice.start_index){right_slice.end_index+=len}stack.push({start_index:right_slice.start_index,end_index:right_slice.end_index});stack.push({start_index:slice.start_index,end_index:slice.end_index})}while(stack.length!==0){slice=stack.pop();end_pt=contour[slice.end_index%len];start_pt=contour[k=slice.start_index%len];if(++k===len){k=0}if(slice.end_index<=slice.start_index+1){le_eps=true}else{max_dist=0;dx=end_pt.x-start_pt.x;dy=end_pt.y-start_pt.y;for(i=slice.start_index+1;i<slice.end_index;++i){pt=contour[k];if(++k===len){k=0}dist=Math.abs((pt.y-start_pt.y)*dx-(pt.x-start_pt.x)*dy);if(dist>max_dist){max_dist=dist;right_slice.start_index=i}}le_eps=max_dist*max_dist<=epsilon*(dx*dx+dy*dy)}if(le_eps){poly.push({x:start_pt.x,y:start_pt.y})}else{right_slice.end_index=slice.end_index;slice.end_index=right_slice.start_index;stack.push({start_index:right_slice.start_index,end_index:right_slice.end_index});stack.push({start_index:slice.start_index,end_index:slice.end_index})}}return poly};CV.warp=function(imageSrc,imageDst,contour,warpSize){var src=imageSrc.data,dst=imageDst.data,width=imageSrc.width,height=imageSrc.height,pos=0,sx1,sx2,dx1,dx2,sy1,sy2,dy1,dy2,p1,p2,p3,p4,m,r,s,t,u,v,w,x,y,i,j;m=CV.getPerspectiveTransform(contour,warpSize-1);r=m[8];s=m[2];t=m[5];for(i=0;i<warpSize;++i){r+=m[7];s+=m[1];t+=m[4];u=r;v=s;w=t;for(j=0;j<warpSize;++j){u+=m[6];v+=m[0];w+=m[3];x=v/u;y=w/u;sx1=x>>>0;sx2=sx1===width-1?sx1:sx1+1;dx1=x-sx1;dx2=1-dx1;sy1=y>>>0;sy2=sy1===height-1?sy1:sy1+1;dy1=y-sy1;dy2=1-dy1;p1=p2=sy1*width;p3=p4=sy2*width;dst[pos++]=dy2*(dx2*src[p1+sx1]+dx1*src[p2+sx2])+dy1*(dx2*src[p3+sx1]+dx1*src[p4+sx2])&255}}imageDst.width=warpSize;imageDst.height=warpSize;return imageDst};CV.getPerspectiveTransform=function(src,size){var rq=CV.square2quad(src);rq[0]/=size;rq[1]/=size;rq[3]/=size;rq[4]/=size;rq[6]/=size;rq[7]/=size;return rq};CV.square2quad=function(src){var sq=[],px,py,dx1,dx2,dy1,dy2,den;px=src[0].x-src[1].x+src[2].x-src[3].x;py=src[0].y-src[1].y+src[2].y-src[3].y;if(0===px&&0===py){sq[0]=src[1].x-src[0].x;sq[1]=src[2].x-src[1].x;sq[2]=src[0].x;sq[3]=src[1].y-src[0].y;sq[4]=src[2].y-src[1].y;sq[5]=src[0].y;sq[6]=0;sq[7]=0;sq[8]=1}else{dx1=src[1].x-src[2].x;dx2=src[3].x-src[2].x;dy1=src[1].y-src[2].y;dy2=src[3].y-src[2].y;den=dx1*dy2-dx2*dy1;sq[6]=(px*dy2-dx2*py)/den;sq[7]=(dx1*py-px*dy1)/den;sq[8]=1;sq[0]=src[1].x-src[0].x+sq[6]*src[1].x;sq[1]=src[3].x-src[0].x+sq[7]*src[3].x;sq[2]=src[0].x;sq[3]=src[1].y-src[0].y+sq[6]*src[1].y;sq[4]=src[3].y-src[0].y+sq[7]*src[3].y;sq[5]=src[0].y}return sq};CV.isContourConvex=function(contour){var orientation=0,convex=true,len=contour.length,i=0,j=0,cur_pt,prev_pt,dxdy0,dydx0,dx0,dy0,dx,dy;prev_pt=contour[len-1];cur_pt=contour[0];dx0=cur_pt.x-prev_pt.x;dy0=cur_pt.y-prev_pt.y;for(;i<len;++i){if(++j===len){j=0}prev_pt=cur_pt;cur_pt=contour[j];dx=cur_pt.x-prev_pt.x;dy=cur_pt.y-prev_pt.y;dxdy0=dx*dy0;dydx0=dy*dx0;orientation|=dydx0>dxdy0?1:dydx0<dxdy0?2:3;if(3===orientation){convex=false;break}dx0=dx;dy0=dy}return convex};CV.perimeter=function(poly){var len=poly.length,i=0,j=len-1,p=0,dx,dy;for(;i<len;j=i++){dx=poly[i].x-poly[j].x;dy=poly[i].y-poly[j].y;p+=Math.sqrt(dx*dx+dy*dy)}return p};CV.minEdgeLength=function(poly){var len=poly.length,i=0,j=len-1,min=Infinity,d,dx,dy;for(;i<len;j=i++){dx=poly[i].x-poly[j].x;dy=poly[i].y-poly[j].y;d=dx*dx+dy*dy;if(d<min){min=d}}return Math.sqrt(min)};CV.countNonZero=function(imageSrc,square){var src=imageSrc.data,height=square.height,width=square.width,pos=square.x+square.y*imageSrc.width,span=imageSrc.width-width,nz=0,i,j;for(i=0;i<height;++i){for(j=0;j<width;++j){if(0!==src[pos++]){++nz}}pos+=span}return nz};CV.binaryBorder=function(imageSrc,dst){var src=imageSrc.data,height=imageSrc.height,width=imageSrc.width,posSrc=0,posDst=0,i,j;for(j=-2;j<width;++j){dst[posDst++]=0}for(i=0;i<height;++i){dst[posDst++]=0;for(j=0;j<width;++j){dst[posDst++]=0===src[posSrc++]?0:1}dst[posDst++]=0}for(j=-2;j<width;++j){dst[posDst++]=0}return dst};var POS=POS||{};POS.Posit=function(modelSize,focalLength){this.objectPoints=this.buildModel(modelSize);this.focalLength=focalLength;this.objectVectors=[];this.objectNormal=[];this.objectMatrix=[[],[],[]];this.init()};POS.Posit.prototype.buildModel=function(modelSize){var half=modelSize/2;return[[-half,half,0],[half,half,0],[half,-half,0],[-half,-half,0]]};POS.Posit.prototype.init=function(){var np=this.objectPoints.length,vectors=[],n=[],len=0,row=2,i;for(i=0;i<np;++i){this.objectVectors[i]=[this.objectPoints[i][0]-this.objectPoints[0][0],this.objectPoints[i][1]-this.objectPoints[0][1],this.objectPoints[i][2]-this.objectPoints[0][2]];vectors[i]=[this.objectVectors[i][0],this.objectVectors[i][1],this.objectVectors[i][2]]}while(0===len){n[0]=this.objectVectors[1][1]*this.objectVectors[row][2]-this.objectVectors[1][2]*this.objectVectors[row][1];n[1]=this.objectVectors[1][2]*this.objectVectors[row][0]-this.objectVectors[1][0]*this.objectVectors[row][2];n[2]=this.objectVectors[1][0]*this.objectVectors[row][1]-this.objectVectors[1][1]*this.objectVectors[row][0];len=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);++row}for(i=0;i<3;++i){this.objectNormal[i]=n[i]/len}POS.pseudoInverse(vectors,np,this.objectMatrix)};POS.Posit.prototype.pose=function(imagePoints){var posRotation1=[[],[],[]],posRotation2=[[],[],[]],posTranslation=[],rotation1=[[],[],[]],rotation2=[[],[],[]],translation1=[],translation2=[],error1,error2,valid1,valid2,i,j;this.pos(imagePoints,posRotation1,posRotation2,posTranslation);valid1=this.isValid(posRotation1,posTranslation);if(valid1){error1=this.iterate(imagePoints,posRotation1,posTranslation,rotation1,translation1)}else{error1={euclidean:-1,pixels:-1,maximum:-1}}valid2=this.isValid(posRotation2,posTranslation);if(valid2){error2=this.iterate(imagePoints,posRotation2,posTranslation,rotation2,translation2)}else{error2={euclidean:-1,pixels:-1,maximum:-1}}for(i=0;i<3;++i){for(j=0;j<3;++j){if(valid1){translation1[i]-=rotation1[i][j]*this.objectPoints[0][j]}if(valid2){translation2[i]-=rotation2[i][j]*this.objectPoints[0][j]}}}return error1.euclidean<error2.euclidean?new POS.Pose(error1.pixels,rotation1,translation1,error2.pixels,rotation2,translation2):new POS.Pose(error2.pixels,rotation2,translation2,error1.pixels,rotation1,translation1)};POS.Posit.prototype.pos=function(imagePoints,rotation1,rotation2,translation){var np=this.objectPoints.length,imageVectors=[],i0=[],j0=[],ivec=[],jvec=[],row1=[],row2=[],row3=[],i0i0,j0j0,i0j0,delta,q,lambda,mu,scale,i,j;for(i=0;i<np;++i){imageVectors[i]=[imagePoints[i].x-imagePoints[0].x,imagePoints[i].y-imagePoints[0].y]}for(i=0;i<3;++i){i0[i]=0;j0[i]=0;for(j=0;j<np;++j){i0[i]+=this.objectMatrix[i][j]*imageVectors[j][0];j0[i]+=this.objectMatrix[i][j]*imageVectors[j][1]}}i0i0=i0[0]*i0[0]+i0[1]*i0[1]+i0[2]*i0[2];j0j0=j0[0]*j0[0]+j0[1]*j0[1]+j0[2]*j0[2];i0j0=i0[0]*j0[0]+i0[1]*j0[1]+i0[2]*j0[2];delta=(j0j0-i0i0)*(j0j0-i0i0)+4*(i0j0*i0j0);if(j0j0-i0i0>=0){q=(j0j0-i0i0+Math.sqrt(delta))/2}else{q=(j0j0-i0i0-Math.sqrt(delta))/2}if(q>=0){lambda=Math.sqrt(q);if(0===lambda){mu=0}else{mu=-i0j0/lambda}}else{lambda=Math.sqrt(-(i0j0*i0j0)/q);if(0===lambda){mu=Math.sqrt(i0i0-j0j0)}else{mu=-i0j0/lambda}}for(i=0;i<3;++i){ivec[i]=i0[i]+lambda*this.objectNormal[i];jvec[i]=j0[i]+mu*this.objectNormal[i]}scale=Math.sqrt(ivec[0]*ivec[0]+ivec[1]*ivec[1]+ivec[2]*ivec[2]);for(i=0;i<3;++i){row1[i]=ivec[i]/scale;row2[i]=jvec[i]/scale}row3[0]=row1[1]*row2[2]-row1[2]*row2[1];row3[1]=row1[2]*row2[0]-row1[0]*row2[2];row3[2]=row1[0]*row2[1]-row1[1]*row2[0];for(i=0;i<3;++i){rotation1[0][i]=row1[i];rotation1[1][i]=row2[i];rotation1[2][i]=row3[i]}for(i=0;i<3;++i){ivec[i]=i0[i]-lambda*this.objectNormal[i];jvec[i]=j0[i]-mu*this.objectNormal[i]}for(i=0;i<3;++i){row1[i]=ivec[i]/scale;row2[i]=jvec[i]/scale}row3[0]=row1[1]*row2[2]-row1[2]*row2[1];row3[1]=row1[2]*row2[0]-row1[0]*row2[2];row3[2]=row1[0]*row2[1]-row1[1]*row2[0];for(i=0;i<3;++i){rotation2[0][i]=row1[i];rotation2[1][i]=row2[i];rotation2[2][i]=row3[i]}translation[0]=imagePoints[0].x/scale;translation[1]=imagePoints[0].y/scale;translation[2]=this.focalLength/scale};POS.Posit.prototype.isValid=function(rotation,translation){var np=this.objectPoints.length,zmin=Infinity,i=0,zi;for(;i<np;++i){zi=translation[2]+(rotation[2][0]*this.objectVectors[i][0]+rotation[2][1]*this.objectVectors[i][1]+rotation[2][2]*this.objectVectors[i][2]);if(zi<zmin){zmin=zi}}return zmin>=0};POS.Posit.prototype.iterate=function(imagePoints,posRotation,posTranslation,rotation,translation){var np=this.objectPoints.length,oldSopImagePoints=[],sopImagePoints=[],rotation1=[[],[],[]],rotation2=[[],[],[]],translation1=[],translation2=[],converged=false,iteration=0,oldImageDifference,imageDifference,factor,error,error1,error2,delta,i,j;for(i=0;i<np;++i){oldSopImagePoints[i]={x:imagePoints[i].x,y:imagePoints[i].y}}for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=posRotation[i][j]}translation[i]=posTranslation[i]}for(i=0;i<np;++i){factor=0;for(j=0;j<3;++j){factor+=this.objectVectors[i][j]*rotation[2][j]/translation[2]}sopImagePoints[i]={x:(1+factor)*imagePoints[i].x,y:(1+factor)*imagePoints[i].y}}imageDifference=0;for(i=0;i<np;++i){imageDifference+=Math.abs(sopImagePoints[i].x-oldSopImagePoints[i].x);imageDifference+=Math.abs(sopImagePoints[i].y-oldSopImagePoints[i].y)}for(i=0;i<3;++i){translation1[i]=translation[i]-(rotation[i][0]*this.objectPoints[0][0]+rotation[i][1]*this.objectPoints[0][1]+rotation[i][2]*this.objectPoints[0][2])}error=error1=this.error(imagePoints,rotation,translation1);converged=0===error1.pixels||imageDifference<.01;while(iteration++<100&&!converged){for(i=0;i<np;++i){oldSopImagePoints[i].x=sopImagePoints[i].x;oldSopImagePoints[i].y=sopImagePoints[i].y}this.pos(sopImagePoints,rotation1,rotation2,translation);for(i=0;i<3;++i){translation1[i]=translation[i]-(rotation1[i][0]*this.objectPoints[0][0]+rotation1[i][1]*this.objectPoints[0][1]+rotation1[i][2]*this.objectPoints[0][2]);translation2[i]=translation[i]-(rotation2[i][0]*this.objectPoints[0][0]+rotation2[i][1]*this.objectPoints[0][1]+rotation2[i][2]*this.objectPoints[0][2])}error1=this.error(imagePoints,rotation1,translation1);error2=this.error(imagePoints,rotation2,translation2);if(error1.euclidean>=0&&error2.euclidean>=0){if(error2.euclidean<error1.euclidean){error=error2;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation2[i][j]}}}else{error=error1;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation1[i][j]}}}}if(error1.euclidean<0&&error2.euclidean>=0){error=error2;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation2[i][j]}}}if(error2.euclidean<0&&error1.euclidean>=0){error=error1;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation1[i][j]}}}for(i=0;i<np;++i){factor=0;for(j=0;j<3;++j){factor+=this.objectVectors[i][j]*rotation[2][j]/translation[2]}sopImagePoints[i].x=(1+factor)*imagePoints[i].x;sopImagePoints[i].y=(1+factor)*imagePoints[i].y}oldImageDifference=imageDifference;imageDifference=0;for(i=0;i<np;++i){imageDifference+=Math.abs(sopImagePoints[i].x-oldSopImagePoints[i].x);imageDifference+=Math.abs(sopImagePoints[i].y-oldSopImagePoints[i].y)}delta=Math.abs(imageDifference-oldImageDifference);converged=0===error.pixels||delta<.01}return error};POS.Posit.prototype.error=function(imagePoints,rotation,translation){var np=this.objectPoints.length,move=[],projection=[],errorvec=[],euclidean=0,pixels=0,maximum=0,i,j,k;if(!this.isValid(rotation,translation)){return{euclidean:-1,pixels:-1,maximum:-1}}for(i=0;i<np;++i){move[i]=[];for(j=0;j<3;++j){move[i][j]=translation[j]}}for(i=0;i<np;++i){for(j=0;j<3;++j){for(k=0;k<3;++k){move[i][j]+=rotation[j][k]*this.objectPoints[i][k]}}}for(i=0;i<np;++i){projection[i]=[];for(j=0;j<2;++j){projection[i][j]=this.focalLength*move[i][j]/move[i][2]}}for(i=0;i<np;++i){errorvec[i]=[projection[i][0]-imagePoints[i].x,projection[i][1]-imagePoints[i].y]}for(i=0;i<np;++i){euclidean+=Math.sqrt(errorvec[i][0]*errorvec[i][0]+errorvec[i][1]*errorvec[i][1]);pixels+=Math.abs(Math.round(projection[i][0])-Math.round(imagePoints[i].x))+Math.abs(Math.round(projection[i][1])-Math.round(imagePoints[i].y));if(Math.abs(errorvec[i][0])>maximum){maximum=Math.abs(errorvec[i][0])}if(Math.abs(errorvec[i][1])>maximum){maximum=Math.abs(errorvec[i][1])}}return{euclidean:euclidean/np,pixels:pixels,maximum:maximum}};POS.pseudoInverse=function(a,n,b){var w=[],v=[[],[],[]],s=[[],[],[]],wmax=0,cn=0,i,j,k;SVD.svdcmp(a,n,3,w,v);for(i=0;i<3;++i){if(w[i]>wmax){wmax=w[i]}}wmax*=.01;for(i=0;i<3;++i){if(w[i]<wmax){w[i]=0}}for(j=0;j<3;++j){if(0===w[j]){++cn;for(k=j;k<2;++k){for(i=0;i<n;++i){a[i][k]=a[i][k+1]}for(i=0;i<3;++i){v[i][k]=v[i][k+1]}}}}for(j=0;j<2;++j){if(0===w[j]){w[j]=w[j+1]}}for(i=0;i<3;++i){for(j=0;j<3-cn;++j){s[i][j]=v[i][j]/w[j]}}for(i=0;i<3;++i){for(j=0;j<n;++j){b[i][j]=0;for(k=0;k<3-cn;++k){b[i][j]+=s[i][k]*a[j][k]}}}};POS.Pose=function(error1,rotation1,translation1,error2,rotation2,translation2){this.bestError=error1;this.bestRotation=rotation1;this.bestTranslation=translation1;this.alternativeError=error2;this.alternativeRotation=rotation2;this.alternativeTranslation=translation2};var SVD=SVD||{};SVD.svdcmp=function(a,m,n,w,v){var flag,i,its,j,jj,k,l,nm,anorm=0,c,f,g=0,h,s,scale=0,x,y,z,rv1=[];for(i=0;i<n;++i){l=i+1;rv1[i]=scale*g;g=s=scale=0;if(i<m){for(k=i;k<m;++k){scale+=Math.abs(a[k][i])}if(0!==scale){for(k=i;k<m;++k){a[k][i]/=scale;s+=a[k][i]*a[k][i]}f=a[i][i];g=-SVD.sign(Math.sqrt(s),f);h=f*g-s;a[i][i]=f-g;for(j=l;j<n;++j){for(s=0,k=i;k<m;++k){s+=a[k][i]*a[k][j]}f=s/h;for(k=i;k<m;++k){a[k][j]+=f*a[k][i]}}for(k=i;k<m;++k){a[k][i]*=scale}}}w[i]=scale*g;g=s=scale=0;if(i<m&&i!==n-1){for(k=l;k<n;++k){scale+=Math.abs(a[i][k])}if(0!==scale){for(k=l;k<n;++k){a[i][k]/=scale;s+=a[i][k]*a[i][k]}f=a[i][l];g=-SVD.sign(Math.sqrt(s),f);h=f*g-s;a[i][l]=f-g;for(k=l;k<n;++k){rv1[k]=a[i][k]/h}for(j=l;j<m;++j){for(s=0,k=l;k<n;++k){s+=a[j][k]*a[i][k]}for(k=l;k<n;++k){a[j][k]+=s*rv1[k]}}for(k=l;k<n;++k){a[i][k]*=scale}}}anorm=Math.max(anorm,Math.abs(w[i])+Math.abs(rv1[i]))}for(i=n-1;i>=0;--i){if(i<n-1){if(0!==g){for(j=l;j<n;++j){v[j][i]=a[i][j]/a[i][l]/g}for(j=l;j<n;++j){for(s=0,k=l;k<n;++k){s+=a[i][k]*v[k][j];
}for(k=l;k<n;++k){v[k][j]+=s*v[k][i]}}}for(j=l;j<n;++j){v[i][j]=v[j][i]=0}}v[i][i]=1;g=rv1[i];l=i}for(i=Math.min(n,m)-1;i>=0;--i){l=i+1;g=w[i];for(j=l;j<n;++j){a[i][j]=0}if(0!==g){g=1/g;for(j=l;j<n;++j){for(s=0,k=l;k<m;++k){s+=a[k][i]*a[k][j]}f=s/a[i][i]*g;for(k=i;k<m;++k){a[k][j]+=f*a[k][i]}}for(j=i;j<m;++j){a[j][i]*=g}}else{for(j=i;j<m;++j){a[j][i]=0}}++a[i][i]}for(k=n-1;k>=0;--k){for(its=1;its<=30;++its){flag=true;for(l=k;l>=0;--l){nm=l-1;if(Math.abs(rv1[l])+anorm===anorm){flag=false;break}if(Math.abs(w[nm])+anorm===anorm){break}}if(flag){c=0;s=1;for(i=l;i<=k;++i){f=s*rv1[i];if(Math.abs(f)+anorm===anorm){break}g=w[i];h=SVD.pythag(f,g);w[i]=h;h=1/h;c=g*h;s=-f*h;for(j=1;j<=m;++j){y=a[j][nm];z=a[j][i];a[j][nm]=y*c+z*s;a[j][i]=z*c-y*s}}}z=w[k];if(l===k){if(z<0){w[k]=-z;for(j=0;j<n;++j){v[j][k]=-v[j][k]}}break}if(30===its){return false}x=w[l];nm=k-1;y=w[nm];g=rv1[nm];h=rv1[k];f=((y-z)*(y+z)+(g-h)*(g+h))/(2*h*y);g=SVD.pythag(f,1);f=((x-z)*(x+z)+h*(y/(f+SVD.sign(g,f))-h))/x;c=s=1;for(j=l;j<=nm;++j){i=j+1;g=rv1[i];y=w[i];h=s*g;g=c*g;z=SVD.pythag(f,h);rv1[j]=z;c=f/z;s=h/z;f=x*c+g*s;g=g*c-x*s;h=y*s;y*=c;for(jj=0;jj<n;++jj){x=v[jj][j];z=v[jj][i];v[jj][j]=x*c+z*s;v[jj][i]=z*c-x*s}z=SVD.pythag(f,h);w[j]=z;if(0!==z){z=1/z;c=f*z;s=h*z}f=c*g+s*y;x=c*y-s*g;for(jj=0;jj<m;++jj){y=a[jj][j];z=a[jj][i];a[jj][j]=y*c+z*s;a[jj][i]=z*c-y*s}}rv1[l]=0;rv1[k]=f;w[k]=x}}return true};SVD.pythag=function(a,b){var at=Math.abs(a),bt=Math.abs(b),ct;if(at>bt){ct=bt/at;return at*Math.sqrt(1+ct*ct)}if(0===bt){return 0}ct=at/bt;return bt*Math.sqrt(1+ct*ct)};SVD.sign=function(a,b){return b>=0?Math.abs(a):-Math.abs(a)};var THREEx=THREEx||{};THREEx.ArucoContext=function(parameters){parameters=parameters||{};this.parameters={debug:parameters.debug!==undefined?parameters.debug:false,canvasWidth:parameters.canvasWidth!==undefined?parameters.canvasWidth:640,canvasHeight:parameters.canvasHeight!==undefined?parameters.canvasHeight:480};this.canvas=document.createElement("canvas");this.detector=new AR.Detector;this.debug=null;if(parameters.debug==true){this.debug=new THREEx.ArucoDebug(this)}this.setSize(this.parameters.canvasWidth,this.parameters.canvasHeight)};THREEx.ArucoContext.prototype.setSize=function(width,height){this.canvas.width=width;this.canvas.height=height;if(this.debug!==null){this.debug.setSize(width,height)}};THREEx.ArucoContext.prototype.detect=function(videoElement){var _this=this;var canvas=this.canvas;var context=canvas.getContext("2d");context.drawImage(videoElement,0,0,canvas.width,canvas.height);var imageData=context.getImageData(0,0,canvas.width,canvas.height);var detectedMarkers=this.detector.detect(imageData);return detectedMarkers};THREEx.ArucoContext.prototype.updateObject3D=function(object3D,arucoPosit,markerSize,detectedMarker){var markerCorners=detectedMarker.corners;var canvas=this.canvas;var poseCorners=new Array(markerCorners.length);for(var i=0;i<markerCorners.length;++i){var markerCorner=markerCorners[i];poseCorners[i]={x:markerCorner.x-canvas.width/2,y:-markerCorner.y+canvas.height/2}}var pose=arucoPosit.pose(poseCorners);var rotation=pose.bestRotation;var translation=pose.bestTranslation;object3D.position.x=translation[0];object3D.position.y=translation[1];object3D.position.z=-translation[2];object3D.rotation.x=-Math.asin(-rotation[1][2]);object3D.rotation.y=-Math.atan2(rotation[0][2],rotation[2][2]);object3D.rotation.z=Math.atan2(rotation[1][0],rotation[1][1]);object3D.scale.x=markerSize;object3D.scale.y=markerSize;object3D.scale.z=markerSize};var THREEx=THREEx||{};AR.Detector.prototype.detect=function(image){var opts=this.datGUIOptions;CV.grayscale(image,this.grey);CV.adaptiveThreshold(this.grey,this.thres,opts.adaptativeThreshold.kernelSize,opts.adaptativeThreshold.threshold);this.contours=CV.findContours(this.thres,this.binary);this.candidates=this.findCandidates(this.contours,image.width*opts.candidates.minSize,opts.candidates.epsilon,opts.candidates.minLength);this.candidates=this.clockwiseCorners(this.candidates);this.candidates=this.notTooNear(this.candidates,opts.notTooNear.minDist);return this.findMarkers(this.grey,this.candidates,opts.findMarkers.warpSize)};AR.Detector.prototype.datGUIOptions={adaptativeThreshold:{kernelSize:2,threshold:7},candidates:{minSize:.2,epsilon:.05,minLength:10},notTooNear:{minDist:10},findMarkers:{warpSize:49}};THREEx.addArucoDatGui=function(arucoContext,datGui){var datGUIOptions=arucoContext.detector.datGUIOptions;var options={resolution:"640x480"};var onChange=function(){var matches=options.resolution.match(/(\d+)x(\d+)/);var width=parseInt(matches[1]);var height=parseInt(matches[2]);arucoContext.setSize(width,height)};onChange();datGui.add(options,"resolution",["320x240","640x480"]).onChange(onChange);var folder=datGui.addFolder("Adaptative Threshold");folder.open();folder.add(arucoContext.detector.datGUIOptions.adaptativeThreshold,"kernelSize").min(0).step(1).onChange(onChange);folder.add(arucoContext.detector.datGUIOptions.adaptativeThreshold,"threshold").min(0).step(1).onChange(onChange);var folder=datGui.addFolder("Candidates");folder.open();folder.add(arucoContext.detector.datGUIOptions.candidates,"minSize").min(0).max(1).onChange(onChange);folder.add(arucoContext.detector.datGUIOptions.candidates,"epsilon").min(0).onChange(onChange);folder.add(arucoContext.detector.datGUIOptions.candidates,"minLength").min(0).step(1).onChange(onChange);var folder=datGui.addFolder("notTooNear");folder.open();folder.add(arucoContext.detector.datGUIOptions.notTooNear,"minDist").min(0).step(1).onChange(onChange);var folder=datGui.addFolder("findMarkers");folder.open();folder.add(arucoContext.detector.datGUIOptions.findMarkers,"warpSize").min(0).step(1).onChange(onChange)};var THREEx=THREEx||{};THREEx.ArucoDebug=function(arucoContext){this.arucoContext=arucoContext;this.canvasElement=document.createElement("canvas");this.canvasElement.width=this.arucoContext.canvas.width;this.canvasElement.height=this.arucoContext.canvas.height};THREEx.ArucoDebug.prototype.setSize=function(width,height){if(this.canvasElement.width!==width)this.canvasElement.width=width;if(this.canvasElement.height!==height)this.canvasElement.height=height};THREEx.ArucoDebug.prototype.clear=function(){var canvas=this.canvasElement;var context=canvas.getContext("2d");context.clearRect(0,0,canvas.width,canvas.height)};THREEx.ArucoDebug.prototype.drawContoursContours=function(){var contours=this.arucoContext.detector.contours;var canvas=this.canvasElement;this.drawContours(contours,0,0,canvas.width,canvas.height,function(hole){return hole?"magenta":"blue"})};THREEx.ArucoDebug.prototype.drawContoursPolys=function(){var contours=this.arucoContext.detector.polys;var canvas=this.canvasElement;this.drawContours(contours,0,0,canvas.width,canvas.height,function(){return"green"})};THREEx.ArucoDebug.prototype.drawContoursCandidates=function(){var contours=this.arucoContext.detector.candidates;var canvas=this.canvasElement;this.drawContours(contours,0,0,canvas.width,canvas.height,function(){return"red"})};THREEx.ArucoDebug.prototype.drawContours=function(contours,x,y,width,height,fn){var i=contours.length,j,contour,point;var canvas=this.canvasElement;var context=canvas.getContext("2d");context.save();while(i--){contour=contours[i];context.strokeStyle=fn(contour.hole);context.beginPath();for(j=0;j<contour.length;++j){point=contour[j];context.moveTo(x+point.x,y+point.y);point=contour[(j+1)%contour.length];context.lineTo(x+point.x,y+point.y)}context.stroke();context.closePath()}context.restore()};THREEx.ArucoDebug.prototype.drawDetectorGrey=function(){var cvImage=arucoContext.detector.grey;this.drawCVImage(cvImage)};THREEx.ArucoDebug.prototype.drawDetectorThreshold=function(){var cvImage=arucoContext.detector.thres;this.drawCVImage(cvImage)};THREEx.ArucoDebug.prototype.drawCVImage=function(cvImage){var detector=this.arucoContext.detector;var canvas=this.canvasElement;var context=canvas.getContext("2d");var imageData=context.createImageData(canvas.width,canvas.height);this.copyCVImage2ImageData(cvImage,imageData);context.putImageData(imageData,0,0)};THREEx.ArucoDebug.prototype.copyCVImage2ImageData=function(cvImage,imageData){var i=cvImage.data.length,j=i*4+3;while(i--){imageData.data[j-=4]=255;imageData.data[j-1]=imageData.data[j-2]=imageData.data[j-3]=cvImage.data[i]}return imageData};THREEx.ArucoDebug.prototype.drawVideo=function(videoElement){var canvas=this.canvasElement;var context=canvas.getContext("2d");context.drawImage(videoElement,0,0,canvas.width,canvas.height)};THREEx.ArucoDebug.prototype.drawMarkerIDs=function(markers){var canvas=this.canvasElement;var context=canvas.getContext("2d");var corners,corner,x,y,i,j;context.save();context.strokeStyle="blue";context.lineWidth=1;for(i=0;i!==markers.length;++i){corners=markers[i].corners;x=Infinity;y=Infinity;for(j=0;j!==corners.length;++j){corner=corners[j];x=Math.min(x,corner.x);y=Math.min(y,corner.y)}context.strokeText(markers[i].id,x,y)}context.restore()};THREEx.ArucoDebug.prototype.drawMarkerCorners=function(markers){var canvas=this.canvasElement;var corners,corner,i,j;var context=canvas.getContext("2d");context.save();context.lineWidth=3;for(i=0;i<markers.length;++i){corners=markers[i].corners;context.strokeStyle="red";context.beginPath();for(j=0;j<corners.length;++j){corner=corners[j];context.moveTo(corner.x,corner.y);corner=corners[(j+1)%corners.length];context.lineTo(corner.x,corner.y)}context.stroke();context.closePath();context.strokeStyle="green";context.strokeRect(corners[0].x-2,corners[0].y-2,4,4)}context.restore()};var THREEx=THREEx||{};THREEx.ArucoMarkerGenerator=function(){};THREEx.ArucoMarkerGenerator.createSVG=function(markerId,svgSize){var domElement=document.createElement("div");domElement.innerHTML=new ArucoMarker(markerId).toSVG(svgSize);return domElement};THREEx.ArucoMarkerGenerator.createImage=function(markerId,width){var canvas=this.createCanvas(markerId,width);var imageURL=canvas.toDataURL();var imageElement=document.createElement("img");imageElement.src=imageURL;return imageElement};THREEx.ArucoMarkerGenerator.createCanvas=function(markerId,width){var canvas=document.createElement("canvas");var context=canvas.getContext("2d");canvas.width=width;canvas.height=width;var arucoMarker=new ArucoMarker(markerId);var marker=arucoMarker.markerMatrix();var margin=canvas.width*.1;var innerW=width-margin*2;var squareW=innerW/7;context.fillStyle="white";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="black";context.fillRect(margin,margin,canvas.width-margin*2,canvas.height-margin*2);for(var y=0;y<5;y++){for(var x=0;x<5;x++){if(marker[x][y]!==1)continue;context.fillStyle="white";context.fillRect(margin+(x+1)*squareW,margin+(y+1)*squareW,squareW+1,squareW+1)}}return canvas};var THREE=THREE||require("three");THREE.WebAR={};THREE.WebAR.MAX_FLOAT32_VALUE=3.4028e38;THREE.WebAR.VRPointCloud=function(vrDisplay){this._vrDisplay=vrDisplay;this._numberOfPointsInLastPointCloud=0;this._bufferGeometry=new THREE.BufferGeometry;this._bufferGeometry.frustumCulled=false;var positions=null;if(vrDisplay){this._pointCloud=new VRPointCloud;vrDisplay.getPointCloud(this._pointCloud,false,0,false);positions=this._pointCloud.points}else{positions=new Float32Array([-1,1,-2,1,1,-2,1,-1,-2,-1,-1,-2])}var colors=new Float32Array(positions.length);var color=new THREE.Color;for(var i=0;i<colors.length;i+=3){if(vrDisplay){positions[i]=THREE.WebAR.MAX_FLOAT32_VALUE;positions[i+1]=THREE.WebAR.MAX_FLOAT32_VALUE;positions[i+2]=THREE.WebAR.MAX_FLOAT32_VALUE}color.setRGB(1,1,1);colors[i]=color.r;colors[i+1]=color.g;colors[i+2]=color.b}this._positions=new THREE.BufferAttribute(positions,3);this._bufferGeometry.addAttribute("position",this._positions);this._colors=new THREE.BufferAttribute(colors,3);this._bufferGeometry.addAttribute("color",this._colors);this._bufferGeometry.computeBoundingSphere();return this};THREE.WebAR.VRPointCloud.prototype.getBufferGeometry=function(){return this._bufferGeometry};THREE.WebAR.VRPointCloud.prototype.update=function(updateBufferGeometry,pointsToSkip,transformPoints){if(!this._vrDisplay)return;this._vrDisplay.getPointCloud(this._pointCloud,!updateBufferGeometry,typeof pointsToSkip==="number"?pointsToSkip:0,!!transformPoints);if(!updateBufferGeometry)return;if(this._pointCloud.numberOfPoints>0){this._positions.needsUpdate=true}};THREE.WebAR.getIndexFromOrientation=function(orientation){var index=0;switch(orientation){case 90:index=1;break;case 180:index=2;break;case 270:index=3;break;default:index=0;break}return index};THREE.WebAR.getIndexFromScreenAndSeeThroughCameraOrientations=function(vrDisplay){var screenOrientation=screen.orientation.angle;var seeThroughCamera=vrDisplay?vrDisplay.getSeeThroughCamera():null;var seeThroughCameraOrientation=seeThroughCamera?seeThroughCamera.orientation:0;var seeThroughCameraOrientationIndex=THREE.WebAR.getIndexFromOrientation(seeThroughCameraOrientation);var screenOrientationIndex=THREE.WebAR.getIndexFromOrientation(screenOrientation);ret=screenOrientationIndex-seeThroughCameraOrientationIndex;if(ret<0){ret+=4}return ret%4};THREE.WebAR.createVRSeeThroughCameraMesh=function(vrDisplay,fallbackVideoPath){var video;var geometry=new THREE.BufferGeometry;if(vrDisplay){var seeThroughCamera=vrDisplay.getSeeThroughCamera();if(!seeThroughCamera)throw"ERROR: Could not get the see through camera!";video=seeThroughCamera;video.readyState=2;video.HAVE_CURRENT_DATA=2;var u=seeThroughCamera.width/seeThroughCamera.textureWidth;var v=seeThroughCamera.height/seeThroughCamera.textureHeight;geometry.WebAR_textureCoords=[new Float32Array([0,0,0,v,u,0,u,v]),new Float32Array([u,0,0,0,u,v,0,v]),new Float32Array([u,v,u,0,0,v,0,0]),new Float32Array([0,v,u,v,0,0,u,0])]}else{var video=document.createElement("video");video.src=typeof fallbackVideoPath==="string"?fallbackVideoPath:"../../resources/videos/sintel.webm";video.play();geometry.WebAR_textureCoords=[new Float32Array([0,0,0,1,1,0,1,1]),new Float32Array([1,0,0,0,1,1,0,1]),new Float32Array([1,1,1,0,0,1,0,0]),new Float32Array([0,1,1,1,0,0,1,0])]}geometry.addAttribute("position",new THREE.BufferAttribute(new Float32Array([-1,1,0,-1,-1,0,1,1,0,1,-1,0]),3));geometry.setIndex(new THREE.BufferAttribute(new Uint16Array([0,1,2,2,1,3]),1));geometry.WebAR_textureCoordIndex=THREE.WebAR.getIndexFromScreenAndSeeThroughCameraOrientations(vrDisplay);var textureCoords=geometry.WebAR_textureCoords[geometry.WebAR_textureCoordIndex];geometry.addAttribute("uv",new THREE.BufferAttribute(new Float32Array(textureCoords),2));geometry.computeBoundingSphere();var videoTexture=new THREE.VideoTexture(video);videoTexture.minFilter=THREE.NearestFilter;videoTexture.magFilter=THREE.NearestFilter;videoTexture.format=THREE.RGBFormat;videoTexture.flipY=false;var material;if(vrDisplay){var vertexShaderSource=["attribute vec3 position;","attribute vec2 uv;","","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","","varying vec2 vUV;","","void main(void) {"," gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);"," vUV = uv;","}"];var fragmentShaderSource=["#extension GL_OES_EGL_image_external : require","precision mediump float;","","varying vec2 vUV;","","uniform samplerExternalOES map;","","void main(void) {"," gl_FragColor = texture2D(map, vUV);","}"];material=new THREE.RawShaderMaterial({uniforms:{map:{type:"t",value:videoTexture}},vertexShader:vertexShaderSource.join("\r\n"),fragmentShader:fragmentShaderSource.join("\r\n"),side:THREE.DoubleSide})}else{material=new THREE.MeshBasicMaterial({color:16777215,side:THREE.DoubleSide,map:videoTexture})}var mesh=new THREE.Mesh(geometry,material);return mesh};THREE.WebAR.updateCameraMeshOrientation=function(vrDisplay,cameraMesh){var textureCoordIndex=THREE.WebAR.getIndexFromScreenAndSeeThroughCameraOrientations(vrDisplay);if(textureCoordIndex!=cameraMesh.geometry.WebAR_textureCoordIndex){var uvs=cameraMesh.geometry.getAttribute("uv");var textureCoords=cameraMesh.geometry.WebAR_textureCoords[textureCoordIndex];cameraMesh.geometry.WebAR_textureCoordIndex=textureCoordIndex;for(var i=0;i<uvs.length;i++){uvs.array[i]=textureCoords[i]}uvs.needsUpdate=true}};THREE.WebAR.createVRSeeThroughCamera=function(vrDisplay,near,far){var camera=new THREE.PerspectiveCamera(60,window.innerWidth/window.innerHeight,near,far);if(vrDisplay){THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay,camera)}return camera};THREE.WebAR.resizeVRSeeThroughCamera=function(vrDisplay,camera){camera.aspect=window.innerWidth/window.innerHeight;if(vrDisplay){var windowWidthBiggerThanHeight=window.innerWidth>window.innerHeight;var seeThroughCamera=vrDisplay.getSeeThroughCamera();if(seeThroughCamera){var cameraWidthBiggerThanHeight=seeThroughCamera.width>seeThroughCamera.height;var swapWidthAndHeight=!(windowWidthBiggerThanHeight&&cameraWidthBiggerThanHeight);var width=swapWidthAndHeight?seeThroughCamera.height:seeThroughCamera.width;var height=swapWidthAndHeight?seeThroughCamera.width:seeThroughCamera.height;var fx=swapWidthAndHeight?seeThroughCamera.focalLengthY:seeThroughCamera.focalLengthX;var fy=swapWidthAndHeight?seeThroughCamera.focalLengthX:seeThroughCamera.focalLengthY;var cx=swapWidthAndHeight?seeThroughCamera.pointY:seeThroughCamera.pointX;var cy=swapWidthAndHeight?seeThroughCamera.pointX:seeThroughCamera.pointY;var xscale=camera.near/fx;var yscale=camera.near/fy;var xoffset=(cx-width/2)*xscale;var yoffset=-(cy-height/2)*yscale;var left=xscale*-width/2-xoffset;var right=xscale*width/2-xoffset;var bottom=yscale*-height/2-yoffset;var top=yscale*height/2-yoffset;camera.projectionMatrix.makePerspective(left,right,top,bottom,camera.near,camera.far);camera.fov=THREE.Math.radToDeg(Math.atan(top*camera.zoom/camera.near))*2}}else{camera.updateProjectionMatrix()}};THREE.WebAR._worldUp=new THREE.Vector3(0,1,0);THREE.WebAR._normalY=new THREE.Vector3;THREE.WebAR._normalZ=new THREE.Vector3;THREE.WebAR._rotationMatrix=new THREE.Matrix4;THREE.WebAR._planeNormal=new THREE.Vector3;THREE.WebAR.rotateObject3D=function(normal1,normal2,object3d){if(normal1 instanceof THREE.Vector3||normal1 instanceof THREE.Vector4){THREE.WebAR._planeNormal.set(normal1.x,normal1.y,normal1.z)}else if(normal1 instanceof Float32Array){THREE.WebAR._planeNormal.set(normal1[0],normal1[1],normal1[2])}else{throw"Unknown normal1 type."}if(normal2 instanceof THREE.Vector3||normal2 instanceof THREE.Vector4){THREE.WebAR._normalZ.set(normal2.x,normal2.y,normal2.z)}else if(normal1 instanceof Float32Array){THREE.WebAR._normalZ.set(normal2[0],normal2[1],normal2[2])}else{throw"Unknown normal2 type."}THREE.WebAR._normalY.crossVectors(THREE.WebAR._planeNormal,THREE.WebAR._normalZ).normalize();THREE.WebAR._rotationMatrix.elements[0]=THREE.WebAR._planeNormal.x;THREE.WebAR._rotationMatrix.elements[1]=THREE.WebAR._planeNormal.y;THREE.WebAR._rotationMatrix.elements[2]=THREE.WebAR._planeNormal.z;THREE.WebAR._rotationMatrix.elements[4]=THREE.WebAR._normalZ.x;THREE.WebAR._rotationMatrix.elements[5]=THREE.WebAR._normalZ.y;THREE.WebAR._rotationMatrix.elements[6]=THREE.WebAR._normalZ.z;THREE.WebAR._rotationMatrix.elements[8]=THREE.WebAR._normalY.x;THREE.WebAR._rotationMatrix.elements[9]=THREE.WebAR._normalY.y;THREE.WebAR._rotationMatrix.elements[10]=THREE.WebAR._normalY.z;object3d.quaternion.setFromRotationMatrix(THREE.WebAR._rotationMatrix)};THREE.WebAR.rotateObject3DWithPickingPlane=function(plane,object3d){if(plane instanceof THREE.Vector3||plane instanceof THREE.Vector4){THREE.WebAR._planeNormal.set(plane.x,plane.y,plane.z)}else if(plane instanceof Float32Array){THREE.WebAR._planeNormal.set(plane[0],plane[1],plane[2])}else{throw"Unknown plane type."}THREE.WebAR._normalY.set(0,1,0);var threshold=.5;if(Math.abs(THREE.WebAR._planeNormal.dot(THREE.WebAR._worldUp))>threshold){THREE.WebAR._normalY.set(0,0,1)}THREE.WebAR._normalZ.crossVectors(THREE.WebAR._planeNormal,THREE.WebAR._normalY).normalize();THREE.WebAR._normalY.crossVectors(THREE.WebAR._normalZ,THREE.WebAR._planeNormal).normalize();THREE.WebAR._rotationMatrix.elements[0]=THREE.WebAR._planeNormal.x;THREE.WebAR._rotationMatrix.elements[1]=THREE.WebAR._planeNormal.y;THREE.WebAR._rotationMatrix.elements[2]=THREE.WebAR._planeNormal.z;THREE.WebAR._rotationMatrix.elements[4]=THREE.WebAR._normalY.x;THREE.WebAR._rotationMatrix.elements[5]=THREE.WebAR._normalY.y;THREE.WebAR._rotationMatrix.elements[6]=THREE.WebAR._normalY.z;THREE.WebAR._rotationMatrix.elements[8]=THREE.WebAR._normalZ.x;THREE.WebAR._rotationMatrix.elements[9]=THREE.WebAR._normalZ.y;THREE.WebAR._rotationMatrix.elements[10]=THREE.WebAR._normalZ.z;object3d.quaternion.setFromRotationMatrix(THREE.WebAR._rotationMatrix)};THREE.WebAR.positionObject3DWithPickingPoint=function(point,object3d){if(point instanceof THREE.Vector3||point instanceof THREE.Vector4){object3d.position.set(point.x,point.y,point.z)}else if(point instanceof Float32Array){object3d.position.set(point[0],point[1],point[2])}else{throw"Unknown point type."}};THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud=function(pointAndPlane,object3d,scale){THREE.WebAR.rotateObject3DWithPickingPlane(pointAndPlane.plane,object3d);THREE.WebAR.positionObject3DWithPickingPoint(pointAndPlane.point,object3d);object3d.position.add(THREE.WebAR._planeNormal.multiplyScalar(scale))};THREE.WebAR.positionAndRotateObject3D=function(position,normal1,normal2,object3d,scale){THREE.WebAR.rotateObject3D(normal1,normal2,object3d);THREE.WebAR.positionObject3DWithPickingPoint(position,object3d);object3d.position.add(THREE.WebAR._planeNormal.multiplyScalar(scale))};(function(root,factory){if(typeof define==="function"&&define.amd){define(["WebAR"],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.WebAR=factory()}})(this,function(){return THREE.WebAR});(function(h){function g(a,b,c,d,e){this._listener=b;this._isOnce=c;this.context=d;this._signal=a;this._priority=e||0}function f(a,b){if(typeof a!=="function")throw Error("listener is a required param of {fn}() and should be a Function.".replace("{fn}",b))}var e={VERSION:"0.7.4"};g.prototype={active:!0,params:null,execute:function(a){var b;this.active&&this._listener&&(a=this.params?this.params.concat(a):a,b=this._listener.apply(this.context,a),this._isOnce&&this.detach());return b},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},getListener:function(){return this._listener},_destroy:function(){delete this._signal;delete this._listener;delete this.context},isOnce:function(){return this._isOnce},toString:function(){return"[SignalBinding isOnce:"+this._isOnce+", isBound:"+this.isBound()+", active:"+this.active+"]"}};e.Signal=function(){this._bindings=[];this._prevParams=null};e.Signal.prototype={memorize:!1,_shouldPropagate:!0,active:!0,_registerListener:function(a,b,c,d){var e=this._indexOfListener(a,c);if(e!==-1){if(a=this._bindings[e],a.isOnce()!==b)throw Error("You cannot add"+(b?"":"Once")+"() then add"+(!b?"":"Once")+"() the same listener without removing the relationship first.")}else a=new g(this,a,b,c,d),this._addBinding(a);this.memorize&&this._prevParams&&a.execute(this._prevParams);return a},_addBinding:function(a){var b=this._bindings.length;do--b;while(this._bindings[b]&&a._priority<=this._bindings[b]._priority);this._bindings.splice(b+1,0,a)},_indexOfListener:function(a,b){for(var c=this._bindings.length,d;c--;)if(d=this._bindings[c],d._listener===a&&d.context===b)return c;return-1},has:function(a,b){return this._indexOfListener(a,b)!==-1},add:function(a,b,c){f(a,"add");return this._registerListener(a,!1,b,c)},addOnce:function(a,b,c){f(a,"addOnce");return this._registerListener(a,!0,b,c)},remove:function(a,b){f(a,"remove");var c=this._indexOfListener(a,b);c!==-1&&(this._bindings[c]._destroy(),this._bindings.splice(c,1));return a},removeAll:function(){for(var a=this._bindings.length;a--;)this._bindings[a]._destroy();this._bindings.length=0},getNumListeners:function(){return this._bindings.length},halt:function(){this._shouldPropagate=!1},dispatch:function(a){if(this.active){var b=Array.prototype.slice.call(arguments),c=this._bindings.length,d;if(this.memorize)this._prevParams=b;if(c){d=this._bindings.slice();this._shouldPropagate=!0;do c--;while(d[c]&&this._shouldPropagate&&d[c].execute(b)!==!1)}}},forget:function(){this._prevParams=null},dispose:function(){this.removeAll();delete this._bindings;delete this._prevParams},toString:function(){return"[Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}};typeof define==="function"&&define.amd?define(e):typeof module!=="undefined"&&module.exports?module.exports=e:h.signals=e})(this);var THREEx=THREEx||{};THREEx.ArBaseControls=function(object3d){this.id=THREEx.ArBaseControls.id++;this.object3d=object3d;this.object3d.matrixAutoUpdate=false;this.object3d.visible=false};THREEx.ArBaseControls.id=0;Object.assign(THREEx.ArBaseControls.prototype,THREE.EventDispatcher.prototype);THREEx.ArBaseControls.prototype.update=function(){console.assert(false,"you need to implement your own update")};THREEx.ArBaseControls.prototype.name=function(){console.assert(false,"you need to implement your own .name()");return"Not yet implemented - name()"};var THREEx=THREEx||{};THREEx.ARClickability=function(sourceElement){this._sourceElement=sourceElement;var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);this._cameraPicking=new THREE.PerspectiveCamera(42,fullWidth/fullHeight,.1,100);console.warn("THREEx.ARClickability works only in modelViewMatrix");console.warn("OBSOLETE OBSOLETE! instead use THREEx.HitTestingPlane or THREEx.HitTestingTango")};THREEx.ARClickability.prototype.onResize=function(){var sourceElement=this._sourceElement;var cameraPicking=this._cameraPicking;var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);cameraPicking.aspect=fullWidth/fullHeight;cameraPicking.updateProjectionMatrix()};THREEx.ARClickability.prototype.computeIntersects=function(domEvent,objects){var sourceElement=this._sourceElement;var cameraPicking=this._cameraPicking;var eventCoords=new THREE.Vector3;eventCoords.x=domEvent.layerX/parseInt(sourceElement.style.width)*2-1;eventCoords.y=-(domEvent.layerY/parseInt(sourceElement.style.height))*2+1;var raycaster=new THREE.Raycaster;raycaster.setFromCamera(eventCoords,cameraPicking);var intersects=raycaster.intersectObjects(objects);return intersects};THREEx.ARClickability.prototype.update=function(){};THREEx.ARClickability.tangoPickingPointCloud=function(artoolkitContext,mouseX,mouseY){var vrDisplay=artoolkitContext._tangoContext.vrDisplay;if(vrDisplay===null)return null;var pointAndPlane=vrDisplay.getPickingPointAndPlaneInPointCloud(mouseX,mouseY);if(pointAndPlane==null){console.warn("Could not retrieve the correct point and plane.");return null}var boundingSphereRadius=.01;var object3d=new THREE.Object3D;THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud(pointAndPlane,object3d,boundingSphereRadius);object3d.rotateZ(-Math.PI/2);var result={};result.position=object3d.position;result.quaternion=object3d.quaternion;return result};var THREEx=THREEx||{};THREEx.ArMarkerCloak=function(videoTexture){var updateInShaderEnabled=true;var geometry=new THREE.PlaneGeometry(1.3+.25,1.85+.25,1,8).translate(0,-.3,0);var material=new THREE.ShaderMaterial({vertexShader:THREEx.ArMarkerCloak.vertexShader,fragmentShader:THREEx.ArMarkerCloak.fragmentShader,transparent:true,uniforms:{texture:{value:videoTexture},opacity:{value:.5}},defines:{updateInShaderEnabled:updateInShaderEnabled?1:0}});var cloakMesh=new THREE.Mesh(geometry,material);cloakMesh.rotation.x=-Math.PI/2;this.object3d=cloakMesh;var xMin=-.65;var xMax=.65;var yMin=.65+.1;var yMax=.95+.1;var originalsFaceVertexUvs=[[]];for(var faceIndex=0;faceIndex<cloakMesh.geometry.faces.length;faceIndex++){originalsFaceVertexUvs[0][faceIndex]=[];originalsFaceVertexUvs[0][faceIndex][0]=new THREE.Vector2;originalsFaceVertexUvs[0][faceIndex][1]=new THREE.Vector2;originalsFaceVertexUvs[0][faceIndex][2]=new THREE.Vector2}for(var i=0;i<cloakMesh.geometry.parameters.heightSegments/2;i++){originalsFaceVertexUvs[0][i*4+0][0].set(xMin/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+0][1].set(xMin/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+0][2].set(xMax/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+1][0].set(xMin/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+1][1].set(xMax/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+1][2].set(xMax/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+2][0].set(xMin/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+2][1].set(xMin/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+2][2].set(xMax/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+3][0].set(xMin/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+3][1].set(xMax/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+3][2].set(xMax/2+.5,yMin/2+.5)}if(updateInShaderEnabled===true){cloakMesh.geometry.faceVertexUvs=originalsFaceVertexUvs;cloakMesh.geometry.uvsNeedUpdate=true}var originalOrthoVertices=[];originalOrthoVertices.push(new THREE.Vector3(xMin,yMax,0));originalOrthoVertices.push(new THREE.Vector3(xMax,yMax,0));originalOrthoVertices.push(new THREE.Vector3(xMin,yMin,0));originalOrthoVertices.push(new THREE.Vector3(xMax,yMin,0));var material=new THREE.MeshNormalMaterial({transparent:true,opacity:.5,side:THREE.DoubleSide});var geometry=new THREE.PlaneGeometry(1,1);var orthoMesh=new THREE.Mesh(geometry,material);this.orthoMesh=orthoMesh;this.update=function(modelViewMatrix,cameraProjectionMatrix){updateOrtho(modelViewMatrix,cameraProjectionMatrix);if(updateInShaderEnabled===false){updateUvs(modelViewMatrix,cameraProjectionMatrix)}};return;function updateUvs(modelViewMatrix,cameraProjectionMatrix){var transformedUv=new THREE.Vector3;originalsFaceVertexUvs[0].forEach(function(faceVertexUvs,faceIndex){faceVertexUvs.forEach(function(originalUv,uvIndex){transformedUv.x=originalUv.x*2-1;transformedUv.y=originalUv.y*2-1;transformedUv.z=0;transformedUv.applyMatrix4(modelViewMatrix);transformedUv.applyMatrix4(cameraProjectionMatrix);transformedUv.x/=transformedUv.z;transformedUv.y/=transformedUv.z;transformedUv.x=transformedUv.x/2+.5;transformedUv.y=transformedUv.y/2+.5;cloakMesh.geometry.faceVertexUvs[0][faceIndex][uvIndex].set(transformedUv.x,transformedUv.y)})});cloakMesh.geometry.uvsNeedUpdate=true}function updateOrtho(modelViewMatrix,cameraProjectionMatrix){var transformedUvs=[];originalOrthoVertices.forEach(function(originalOrthoVertices,index){var transformedUv=originalOrthoVertices.clone();transformedUv.applyMatrix4(modelViewMatrix);transformedUv.applyMatrix4(cameraProjectionMatrix);transformedUv.x/=transformedUv.z;transformedUv.y/=transformedUv.z;transformedUvs.push(transformedUv)});for(var i=0;i<transformedUvs.length;i++){orthoMesh.geometry.vertices[i].copy(transformedUvs[i])}orthoMesh.geometry.computeBoundingSphere();orthoMesh.geometry.verticesNeedUpdate=true}};THREEx.ArMarkerCloak.markerSpaceShaderFunction="\n"+" vec2 transformUvToMarkerSpace(vec2 originalUv){\n"+" vec3 transformedUv;\n"+" // set transformedUv - from UV coord to clip coord\n"+" transformedUv.x = originalUv.x * 2.0 - 1.0;\n"+" transformedUv.y = originalUv.y * 2.0 - 1.0;\n"+" transformedUv.z = 0.0;\n"+"\n"+" // apply modelViewMatrix and projectionMatrix\n"+" transformedUv = (projectionMatrix * modelViewMatrix * vec4( transformedUv, 1.0 ) ).xyz;\n"+"\n"+" // apply perspective\n"+" transformedUv.x /= transformedUv.z;\n"+" transformedUv.y /= transformedUv.z;\n"+"\n"+" // set back from clip coord to Uv coord\n"+" transformedUv.x = transformedUv.x / 2.0 + 0.5;\n"+" transformedUv.y = transformedUv.y / 2.0 + 0.5;\n"+"\n"+" // return the result\n"+" return transformedUv.xy;\n"+" }";THREEx.ArMarkerCloak.vertexShader=THREEx.ArMarkerCloak.markerSpaceShaderFunction+" varying vec2 vUv;\n"+"\n"+" void main(){\n"+" // pass the UV to the fragment\n"+" #if (updateInShaderEnabled == 1)\n"+" vUv = transformUvToMarkerSpace(uv);\n"+" #else\n"+" vUv = uv;\n"+" #endif\n"+"\n"+" // compute gl_Position\n"+" vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n"+" gl_Position = projectionMatrix * mvPosition;\n"+" }";
THREEx.ArMarkerCloak.fragmentShader="\n"+" varying vec2 vUv;\n"+" uniform sampler2D texture;\n"+" uniform float opacity;\n"+"\n"+" void main(void){\n"+" vec3 color = texture2D( texture, vUv ).rgb;\n"+"\n"+" gl_FragColor = vec4( color, opacity);\n"+" }";var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkerControls=THREEx.ArMarkerControls=function(context,object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.context=context;this.parameters={size:1,type:"unknown",patternUrl:null,barcodeValue:null,changeMatrixMode:"modelViewMatrix",minConfidence:.6};var possibleValues=["pattern","barcode","unknown"];console.assert(possibleValues.indexOf(this.parameters.type)!==-1,"illegal value",this.parameters.type);var possibleValues=["modelViewMatrix","cameraTransformMatrix"];console.assert(possibleValues.indexOf(this.parameters.changeMatrixMode)!==-1,"illegal value",this.parameters.changeMatrixMode);this.object3d=object3d;this.object3d.matrixAutoUpdate=false;this.object3d.visible=false;setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}context.addMarker(this);if(_this.context.parameters.trackingBackend==="artoolkit"){this._initArtoolkit()}else if(_this.context.parameters.trackingBackend==="aruco"){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)}else if(_this.context.parameters.trackingBackend==="tango"){this._initTango()}else console.assert(false)};ARjs.MarkerControls.prototype=Object.create(THREEx.ArBaseControls.prototype);ARjs.MarkerControls.prototype.constructor=THREEx.ArMarkerControls;ARjs.MarkerControls.prototype.dispose=function(){this.context.removeMarker(this)};ARjs.MarkerControls.prototype.updateWithModelViewMatrix=function(modelViewMatrix){var markerObject3D=this.object3d;markerObject3D.visible=true;if(this.context.parameters.trackingBackend==="artoolkit"){var tmpMatrix=(new THREE.Matrix4).copy(this.context._artoolkitProjectionAxisTransformMatrix);tmpMatrix.multiply(modelViewMatrix);modelViewMatrix.copy(tmpMatrix)}else if(this.context.parameters.trackingBackend==="aruco"){}else if(this.context.parameters.trackingBackend==="tango"){}else console.assert(false);if(this.context.parameters.trackingBackend!=="tango"){var markerAxisTransformMatrix=(new THREE.Matrix4).makeRotationX(Math.PI/2);modelViewMatrix.multiply(markerAxisTransformMatrix)}if(this.parameters.changeMatrixMode==="modelViewMatrix"){markerObject3D.matrix.copy(modelViewMatrix)}else if(this.parameters.changeMatrixMode==="cameraTransformMatrix"){markerObject3D.matrix.getInverse(modelViewMatrix)}else{console.assert(false)}markerObject3D.matrix.decompose(markerObject3D.position,markerObject3D.quaternion,markerObject3D.scale);this.dispatchEvent({type:"markerFound"})};ARjs.MarkerControls.prototype.name=function(){var name="";name+=this.parameters.type;if(this.parameters.type==="pattern"){var url=this.parameters.patternUrl;var basename=url.replace(/^.*\//g,"");name+=" - "+basename}else if(this.parameters.type==="barcode"){name+=" - "+this.parameters.barcodeValue}else{console.assert(false,"no .name() implemented for this marker controls")}return name};ARjs.MarkerControls.prototype._initArtoolkit=function(){var _this=this;var artoolkitMarkerId=null;var delayedInitTimerId=setInterval(function(){var arController=_this.context.arController;if(arController===null)return;clearInterval(delayedInitTimerId);delayedInitTimerId=null;postInit()},1e3/50);return;function postInit(){var arController=_this.context.arController;console.assert(arController!==null);if(_this.parameters.type==="pattern"){arController.loadMarker(_this.parameters.patternUrl,function(markerId){artoolkitMarkerId=markerId;arController.trackPatternMarkerId(artoolkitMarkerId,_this.parameters.size)})}else if(_this.parameters.type==="barcode"){artoolkitMarkerId=_this.parameters.barcodeValue;arController.trackBarcodeMarkerId(artoolkitMarkerId,_this.parameters.size)}else if(_this.parameters.type==="unknown"){artoolkitMarkerId=null}else{console.log(false,"invalid marker type",_this.parameters.type)}arController.addEventListener("getMarker",function(event){if(event.data.type===artoolkit.PATTERN_MARKER&&_this.parameters.type==="pattern"){if(artoolkitMarkerId===null)return;if(event.data.marker.idPatt===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.BARCODE_MARKER&&_this.parameters.type==="barcode"){if(artoolkitMarkerId===null)return;if(event.data.marker.idMatrix===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.UNKNOWN_MARKER&&_this.parameters.type==="unknown"){onMarkerFound(event)}})}function onMarkerFound(event){if(event.data.type===artoolkit.PATTERN_MARKER&&event.data.marker.cfPatt<_this.parameters.minConfidence)return;if(event.data.type===artoolkit.BARCODE_MARKER&&event.data.marker.cfMatt<_this.parameters.minConfidence)return;var modelViewMatrix=(new THREE.Matrix4).fromArray(event.data.matrix);_this.updateWithModelViewMatrix(modelViewMatrix)}};ARjs.MarkerControls.prototype._initAruco=function(){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)};ARjs.MarkerControls.prototype._initTango=function(){var _this=this;console.log("init tango ArMarkerControls")};var THREEx=THREEx||{};THREEx.ArMarkerHelper=function(markerControls){this.object3d=new THREE.Group;var mesh=new THREE.AxisHelper;this.object3d.add(mesh);var text=markerControls.id;var canvas=document.createElement("canvas");canvas.width=64;canvas.height=64;var context=canvas.getContext("2d");var texture=new THREE.CanvasTexture(canvas);context.font="48px monospace";context.fillStyle="rgba(192,192,255, 0.5)";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="darkblue";context.fillText(text,canvas.width/4,3*canvas.height/4);texture.needsUpdate=true;var geometry=new THREE.PlaneGeometry(1,1);var material=new THREE.MeshBasicMaterial({map:texture,transparent:true});var mesh=new THREE.Mesh(geometry,material);mesh.rotation.x=-Math.PI/2;this.object3d.add(mesh)};var THREEx=THREEx||{};THREEx.ArSmoothedControls=function(object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.object3d.visible=false;this._lastLerpStepAt=null;this._visibleStartedAt=null;this._unvisibleStartedAt=null;parameters=parameters||{};this.parameters={lerpPosition:.8,lerpQuaternion:.2,lerpScale:.7,lerpStepDelay:1/60,minVisibleDelay:0,minUnvisibleDelay:.2};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};THREEx.ArSmoothedControls.prototype=Object.create(THREEx.ArBaseControls.prototype);THREEx.ArSmoothedControls.prototype.constructor=THREEx.ArSmoothedControls;THREEx.ArSmoothedControls.prototype.update=function(targetObject3d){var object3d=this.object3d;var parameters=this.parameters;var wasVisible=object3d.visible;var present=performance.now()/1e3;if(targetObject3d.visible===false)this._visibleStartedAt=null;if(targetObject3d.visible===true)this._unvisibleStartedAt=null;if(targetObject3d.visible===true&&this._visibleStartedAt===null)this._visibleStartedAt=present;if(targetObject3d.visible===false&&this._unvisibleStartedAt===null)this._unvisibleStartedAt=present;if(wasVisible===false&&targetObject3d.visible===true){var visibleFor=present-this._visibleStartedAt;if(visibleFor>=this.parameters.minVisibleDelay){object3d.visible=true;snapDirectlyToTarget()}}if(wasVisible===true&&targetObject3d.visible===false){var unvisibleFor=present-this._unvisibleStartedAt;if(unvisibleFor>=this.parameters.minUnvisibleDelay){object3d.visible=false}}if(this._lastLerpStepAt===null){applyOneSlerpStep();this._lastLerpStepAt=present}else{var nStepsToDo=Math.floor((present-this._lastLerpStepAt)/this.parameters.lerpStepDelay);for(var i=0;i<nStepsToDo;i++){applyOneSlerpStep();this._lastLerpStepAt+=this.parameters.lerpStepDelay}}if(false){snapDirectlyToTarget()}this.object3d.updateMatrix();if(wasVisible===false&&object3d.visible===true){this.dispatchEvent({type:"becameVisible"})}if(wasVisible===true&&object3d.visible===false){this.dispatchEvent({type:"becameUnVisible"})}return;function snapDirectlyToTarget(){object3d.position.copy(targetObject3d.position);object3d.quaternion.copy(targetObject3d.quaternion);object3d.scale.copy(targetObject3d.scale)}function applyOneSlerpStep(){object3d.position.lerp(targetObject3d.position,parameters.lerpPosition);object3d.quaternion.slerp(targetObject3d.quaternion,parameters.lerpQuaternion);object3d.scale.lerp(targetObject3d.scale,parameters.lerpScale)}};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Context=THREEx.ArToolkitContext=function(parameters){var _this=this;_this._updatedAt=null;this.parameters={trackingBackend:"artoolkit",debug:false,detectionMode:"mono",matrixCodeType:"3x3",cameraParametersUrl:ARjs.Context.baseURL+"parameters/camera_para.dat",maxDetectionRate:60,canvasWidth:640,canvasHeight:480,patternRatio:.5,imageSmoothingEnabled:false};console.assert(["artoolkit","aruco","tango"].indexOf(this.parameters.trackingBackend)!==-1,"invalid parameter trackingBackend",this.parameters.trackingBackend);console.assert(["color","color_and_matrix","mono","mono_and_matrix"].indexOf(this.parameters.detectionMode)!==-1,"invalid parameter detectionMode",this.parameters.detectionMode);this.arController=null;this.arucoContext=null;_this.initialized=false;this._arMarkersControls=[];setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};Object.assign(ARjs.Context.prototype,THREE.EventDispatcher.prototype);ARjs.Context.baseURL="https://jeromeetienne.github.io/AR.js/three.js/";ARjs.Context.REVISION="1.6.
1
";ARjs.Context.createDefaultCamera=function(trackingBackend){console.assert(false,"use ARjs.Utils.createDefaultCamera instead");if(trackingBackend==="artoolkit"){var camera=new THREE.Camera}else if(trackingBackend==="aruco"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else if(trackingBackend==="tango"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else console.assert(false);return camera};ARjs.Context.prototype.init=function(onCompleted){var _this=this;if(this.parameters.trackingBackend==="artoolkit"){this._initArtoolkit(done)}else if(this.parameters.trackingBackend==="aruco"){this._initAruco(done)}else if(this.parameters.trackingBackend==="tango"){this._initTango(done)}else console.assert(false);return;function done(){_this.dispatchEvent({type:"initialized"});_this.initialized=true;onCompleted&&onCompleted()}};ARjs.Context.prototype.update=function(srcElement){if(this.parameters.trackingBackend==="artoolkit"&&this.arController===null)return false;var present=performance.now();if(this._updatedAt!==null&&present-this._updatedAt<1e3/this.parameters.maxDetectionRate){return false}this._updatedAt=present;this._arMarkersControls.forEach(function(markerControls){markerControls.object3d.visible=false});if(this.parameters.trackingBackend==="artoolkit"){this._updateArtoolkit(srcElement)}else if(this.parameters.trackingBackend==="aruco"){this._updateAruco(srcElement)}else if(this.parameters.trackingBackend==="tango"){this._updateTango(srcElement)}else{console.assert(false)}this.dispatchEvent({type:"sourceProcessed"});return true};ARjs.Context.prototype.addMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);this._arMarkersControls.push(arMarkerControls)};ARjs.Context.prototype.removeMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);var index=this.arMarkerControlss.indexOf(artoolkitMarker);console.assert(index!==index);this._arMarkersControls.splice(index,1)};ARjs.Context.prototype._initArtoolkit=function(onCompleted){var _this=this;this._artoolkitProjectionAxisTransformMatrix=new THREE.Matrix4;this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationY(Math.PI));this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationZ(Math.PI));var cameraParameters=new ARCameraParam(_this.parameters.cameraParametersUrl,function(){var arController=new ARController(_this.parameters.canvasWidth,_this.parameters.canvasHeight,cameraParameters);_this.arController=arController;arController.ctx.mozImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.webkitImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.msImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.imageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;if(_this.parameters.debug===true){arController.debugSetup();arController.canvas.style.position="absolute";arController.canvas.style.top="0px";arController.canvas.style.opacity="0.6";arController.canvas.style.pointerEvents="none";arController.canvas.style.zIndex="-1"}var detectionModes={color:artoolkit.AR_TEMPLATE_MATCHING_COLOR,color_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX,mono:artoolkit.AR_TEMPLATE_MATCHING_MONO,mono_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_MONO_AND_MATRIX};var detectionMode=detectionModes[_this.parameters.detectionMode];console.assert(detectionMode!==undefined);arController.setPatternDetectionMode(detectionMode);var matrixCodeTypes={"3x3":artoolkit.AR_MATRIX_CODE_3x3,"3x3_HAMMING63":artoolkit.AR_MATRIX_CODE_3x3_HAMMING63,"3x3_PARITY65":artoolkit.AR_MATRIX_CODE_3x3_PARITY65,"4x4":artoolkit.AR_MATRIX_CODE_4x4,"4x4_BCH_13_9_3":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_9_3,"4x4_BCH_13_5_5":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_5_5};var matrixCodeType=matrixCodeTypes[_this.parameters.matrixCodeType];console.assert(matrixCodeType!==undefined);arController.setMatrixCodeType(matrixCodeType);arController.setPattRatio(_this.parameters.patternRatio);onCompleted()});return this};ARjs.Context.prototype.getProjectionMatrix=function(srcElement){console.assert(this.parameters.trackingBackend==="artoolkit");console.assert(this.arController,"arController MUST be initialized to call this function");var projectionMatrixArr=this.arController.getCameraMatrix();var projectionMatrix=(new THREE.Matrix4).fromArray(projectionMatrixArr);projectionMatrix.multiply(this._artoolkitProjectionAxisTransformMatrix);return projectionMatrix};ARjs.Context.prototype._updateArtoolkit=function(srcElement){this.arController.process(srcElement)};ARjs.Context.prototype._initAruco=function(onCompleted){this.arucoContext=new THREEx.ArucoContext;this.arucoContext.canvas.width=this.parameters.canvasWidth;this.arucoContext.canvas.height=this.parameters.canvasHeight;var context=this.arucoContext.canvas.getContext("2d");context.webkitImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.msImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.imageSmoothingEnabled=this.parameters.imageSmoothingEnabled;setTimeout(function(){onCompleted()},0)};ARjs.Context.prototype._updateAruco=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var detectedMarkers=this.arucoContext.detect(srcElement);detectedMarkers.forEach(function(detectedMarker){var foundControls=null;for(var i=0;i<arMarkersControls.length;i++){console.assert(arMarkersControls[i].parameters.type==="barcode");if(arMarkersControls[i].parameters.barcodeValue===detectedMarker.id){foundControls=arMarkersControls[i];break}}if(foundControls===null)return;var tmpObject3d=new THREE.Object3D;_this.arucoContext.updateObject3D(tmpObject3d,foundControls._arucoPosit,foundControls.parameters.size,detectedMarker);tmpObject3d.updateMatrix();foundControls.updateWithModelViewMatrix(tmpObject3d.matrix)})};ARjs.Context.prototype._initTango=function(onCompleted){var _this=this;if(navigator.getVRDisplays){}else if(navigator.getVRDevices){alert("Your browser supports WebVR but not the latest version. See <a href='http://webvr.info'>webvr.info</a> for more info.")}else{alert("Your browser does not support WebVR. See <a href='http://webvr.info'>webvr.info</a> for assistance.")}this._tangoContext={vrDisplay:null,vrPointCloud:null,frameData:new VRFrameData};navigator.getVRDisplays().then(function(vrDisplays){if(vrDisplays.length===0)alert("no vrDisplays available");var vrDisplay=_this._tangoContext.vrDisplay=vrDisplays[0];console.log("vrDisplays.displayName :",vrDisplay.displayName);if(vrDisplay.displayName==="Tango VR Device"){_this._tangoContext.vrPointCloud=new THREE.WebAR.VRPointCloud(vrDisplay,true)}onCompleted()})};ARjs.Context.prototype._updateTango=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var tangoContext=this._tangoContext;var vrDisplay=this._tangoContext.vrDisplay;if(vrDisplay===null)return;if(vrDisplay.displayName==="Tango VR Device"){var showPointCloud=true;var pointsToSkip=0;_this._tangoContext.vrPointCloud.update(showPointCloud,pointsToSkip,true)}if(this._arMarkersControls.length===0)return;var foundControls=this._arMarkersControls[0];var frameData=this._tangoContext.frameData;vrDisplay.getFrameData(frameData);if(frameData.pose.position===null)return;if(frameData.pose.orientation===null)return;var position=(new THREE.Vector3).fromArray(frameData.pose.position);var quaternion=(new THREE.Quaternion).fromArray(frameData.pose.orientation);var scale=new THREE.Vector3(1,1,1);var cameraTransformMatrix=(new THREE.Matrix4).compose(position,quaternion,scale);var modelViewMatrix=new THREE.Matrix4;modelViewMatrix.getInverse(cameraTransformMatrix);foundControls.updateWithModelViewMatrix(modelViewMatrix)};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Profile=THREEx.ArToolkitProfile=function(){this.reset();this.performance("default")};ARjs.Profile.prototype._guessPerformanceLabel=function(){var isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/webOS/i)||navigator.userAgent.match(/iPhone/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPod/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Windows Phone/i)?true:false;if(isMobile===true){return"phone-normal"}return"desktop-normal"};ARjs.Profile.prototype.reset=function(){this.sourceParameters={sourceType:"webcam"};this.contextParameters={cameraParametersUrl:THREEx.ArToolkitContext.baseURL+"../data/data/camera_para.dat",detectionMode:"mono"};this.defaultMarkerParameters={type:"pattern",patternUrl:THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro",changeMatrixMode:"modelViewMatrix"};return this};ARjs.Profile.prototype.performance=function(label){if(label==="default"){label=this._guessPerformanceLabel()}if(label==="desktop-fast"){this.contextParameters.canvasWidth=640*3;this.contextParameters.canvasHeight=480*3;this.contextParameters.maxDetectionRate=30}else if(label==="desktop-normal"){this.contextParameters.canvasWidth=640;this.contextParameters.canvasHeight=480;this.contextParameters.maxDetectionRate=60}else if(label==="phone-normal"){this.contextParameters.canvasWidth=80*4;this.contextParameters.canvasHeight=60*4;this.contextParameters.maxDetectionRate=30}else if(label==="phone-slow"){this.contextParameters.canvasWidth=80*3;this.contextParameters.canvasHeight=60*3;this.contextParameters.maxDetectionRate=30}else{console.assert(false,"unknonwn label "+label)}return this};ARjs.Profile.prototype.defaultMarker=function(trackingBackend){trackingBackend=trackingBackend||this.contextParameters.trackingBackend;if(trackingBackend==="artoolkit"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="pattern";this.defaultMarkerParameters.patternUrl=THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro"}else if(trackingBackend==="aruco"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else if(trackingBackend==="tango"){this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else console.assert(false);return this};ARjs.Profile.prototype.sourceWebcam=function(){this.sourceParameters.sourceType="webcam";delete this.sourceParameters.sourceUrl;return this};ARjs.Profile.prototype.sourceVideo=function(url){this.sourceParameters.sourceType="video";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.sourceImage=function(url){this.sourceParameters.sourceType="image";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.trackingBackend=function(trackingBackend){console.warn("stop profile.trackingBackend() obsolete function. use .trackingMethod instead");this.contextParameters.trackingBackend=trackingBackend;return this};ARjs.Profile.prototype.changeMatrixMode=function(changeMatrixMode){this.defaultMarkerParameters.changeMatrixMode=changeMatrixMode;return this};ARjs.Profile.prototype.trackingMethod=function(trackingMethod){var data=ARjs.Utils.parseTrackingMethod(trackingMethod);this.defaultMarkerParameters.markersAreaEnabled=data.markersAreaEnabled;this.contextParameters.trackingBackend=data.trackingBackend;return this};ARjs.Profile.prototype.checkIfValid=function(){if(this.contextParameters.trackingBackend==="tango"){this.sourceImage(THREEx.ArToolkitContext.baseURL+"../data/images/img.jpg")}return this};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Source=THREEx.ArToolkitSource=function(parameters){var _this=this;this.ready=false;this.domElement=null;this.parameters={sourceType:"webcam",sourceUrl:null,deviceId:null,sourceWidth:640,sourceHeight:480,displayWidth:640,displayHeight:480};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};ARjs.Source.prototype.init=function(onReady,onError){var _this=this;if(this.parameters.sourceType==="image"){var domElement=this._initSourceImage(onSourceReady,onError)}else if(this.parameters.sourceType==="video"){var domElement=this._initSourceVideo(onSourceReady,onError)}else if(this.parameters.sourceType==="webcam"){var domElement=this._initSourceWebcam(onSourceReady,onError)}else{console.assert(false)}this.domElement=domElement;this.domElement.style.position="absolute";this.domElement.style.top="0px";this.domElement.style.left="0px";this.domElement.style.zIndex="-2";return this;function onSourceReady(){document.body.appendChild(_this.domElement);_this.ready=true;onReady&&onReady()}};ARjs.Source.prototype._initSourceImage=function(onReady){var domElement=document.createElement("img");domElement.src=this.parameters.sourceUrl;domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.naturalWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceVideo=function(onReady){var domElement=document.createElement("video");domElement.src=this.parameters.sourceUrl;domElement.style.objectFit="initial";domElement.autoplay=true;domElement.webkitPlaysinline=true;domElement.controls=false;domElement.loop=true;domElement.muted=true;document.body.addEventListener("click",function onClick(){document.body.removeEventListener("click",onClick);domElement.play()});domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceWebcam=function(onReady,onError){var _this=this;onError=onError||function(error){alert("Webcam Error\nName: "+error.name+"\nMessage: "+error.message)};var domElement=document.createElement("video");domElement.setAttribute("autoplay","");domElement.setAttribute("muted","");domElement.setAttribute("playsinline","");domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";if(navigator.mediaDevices===undefined||navigator.mediaDevices.enumerateDevices===undefined||navigator.mediaDevices.getUserMedia===undefined){if(navigator.mediaDevices===undefined)var fctName="navigator.mediaDevices";else if(navigator.mediaDevices.enumerateDevices===undefined)var fctName="navigator.mediaDevices.enumerateDevices";else if(navigator.mediaDevices.getUserMedia===undefined)var fctName="navigator.mediaDevices.getUserMedia";else console.assert(false);onError({name:"",message:"WebRTC issue-! "+fctName+" not present in your browser"});return null}navigator.mediaDevices.enumerateDevices().then(function(devices){var userMediaConstraints={audio:false,video:{facingMode:"environment",width:{ideal:_this.parameters.sourceWidth},height:{ideal:_this.parameters.sourceHeight}}};if(null!==_this.parameters.deviceId){userMediaConstraints.video.deviceId={exact:_this.parameters.deviceId}}navigator.mediaDevices.getUserMedia(userMediaConstraints).then(function success(stream){domElement.srcObject=stream;document.body.addEventListener("click",function(){domElement.play()});var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50)}).catch(function(error){onError({name:error.name,message:error.message})})}).catch(function(error){onError({message:error.message})});return domElement};ARjs.Source.prototype.hasMobileTorch=function(){var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false)return false;if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];if(videoTrack.getCapabilities===undefined)return false;var capabilities=videoTrack.getCapabilities();return capabilities.torch?true:false};ARjs.Source.prototype.toggleMobileTorch=function(){console.assert(this.hasMobileTorch()===true);var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false){alert("enabling mobile torch is available only on webcam");return}if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];var capabilities=videoTrack.getCapabilities();if(!capabilities.torch){alert("no mobile torch is available on your camera");return}this._currentTorchStatus=this._currentTorchStatus===false?true:false;videoTrack.applyConstraints({advanced:[{torch:this._currentTorchStatus}]}).catch(function(error){console.log(error)})};ARjs.Source.prototype.domElementWidth=function(){return parseInt(this.domElement.style.width)};ARjs.Source.prototype.domElementHeight=function(){return parseInt(this.domElement.style.height)};ARjs.Source.prototype.onResizeElement=function(){var _this=this;var screenWidth=window.innerWidth;var screenHeight=window.innerHeight;console.assert(arguments.length===0);if(this.domElement.nodeName==="IMG"){var sourceWidth=this.domElement.naturalWidth;var sourceHeight=this.domElement.naturalHeight}else if(this.domElement.nodeName==="VIDEO"){var sourceWidth=this.domElement.videoWidth;var sourceHeight=this.domElement.videoHeight}else{console.assert(false)}var sourceAspect=sourceWidth/sourceHeight;var screenAspect=screenWidth/screenHeight;if(screenAspect<sourceAspect){var newWidth=sourceAspect*screenHeight;this.domElement.style.width=newWidth+"px";this.domElement.style.marginLeft=-(newWidth-screenWidth)/2+"px";this.domElement.style.height=screenHeight+"px";this.domElement.style.marginTop="0px"}else{var newHeight=1/(sourceAspect/screenWidth);this.domElement.style.height=newHeight+"px";this.domElement.style.marginTop=-(newHeight-screenHeight)/2+"px";this.domElement.style.width=screenWidth+"px";this.domElement.style.marginLeft="0px"}};ARjs.Source.prototype.copyElementSizeTo=function(otherElement){if(window.innerWidth>window.innerHeight){otherElement.style.width=this.domElement.style.width;otherElement.style.height=this.domElement.style.height;otherElement.style.marginLeft=this.domElement.style.marginLeft;otherElement.style.marginTop=this.domElement.style.marginTop}else{otherElement.style.height=this.domElement.style.height;otherElement.style.width=parseInt(otherElement.style.height)*4/3+"px";otherElement.style.marginLeft=(window.innerWidth-parseInt(otherElement.style.width))/2+"px";otherElement.style.marginTop=0}};ARjs.Source.prototype.copySizeTo=function(){console.warn("obsolete function arToolkitSource.copySizeTo. Use arToolkitSource.copyElementSizeTo");this.copyElementSizeTo.apply(this,arguments)};ARjs.Source.prototype.onResize=function(arToolkitContext,renderer,camera){if(arguments.length!==3){console.warn("obsolete function arToolkitSource.onResize. Use arToolkitSource.onResizeElement");return this.onResizeElement.apply(this,arguments)}var trackingBackend=arToolkitContext.parameters.trackingBackend;if(trackingBackend==="artoolkit"){this.onResizeElement();var isAframe=renderer.domElement.dataset.aframeCanvas?true:false;if(isAframe===false){this.copyElementSizeTo(renderer.domElement)}else{}if(arToolkitContext.arController!==null){this.copyElementSizeTo(arToolkitContext.arController.canvas)}}else if(trackingBackend==="aruco"){this.onResizeElement();this.copyElementSizeTo(renderer.domElement);this.copyElementSizeTo(arToolkitContext.arucoContext.canvas)}else if(trackingBackend==="tango"){renderer.setSize(window.innerWidth,window.innerHeight)}else console.assert(false,"unhandled trackingBackend "+trackingBackend);if(trackingBackend==="artoolkit"){if(arToolkitContext.arController!==null){camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix())}}else if(trackingBackend==="aruco"){camera.aspect=renderer.domElement.width/renderer.domElement.height;camera.updateProjectionMatrix()}else if(trackingBackend==="tango"){var vrDisplay=arToolkitContext._tangoContext.vrDisplay;if(vrDisplay&&vrDisplay.displayName==="Tango VR Device")THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay,camera)}else console.assert(false,"unhandled trackingBackend "+trackingBackend)};var THREEx=THREEx||{};THREEx.ArVideoInWebgl=function(videoTexture){var _this=this;var geometry=new THREE.PlaneGeometry(2,2);var material=new THREE.MeshBasicMaterial({map:videoTexture});var seethruPlane=new THREE.Mesh(geometry,material);this.object3d=seethruPlane;this.update=function(camera){camera.updateMatrixWorld(true);var position=new THREE.Vector3(-0,0,-20);var position=new THREE.Vector3(-0,0,-20);seethruPlane.position.copy(position);camera.localToWorld(seethruPlane.position);camera.matrixWorld.decompose(camera.position,camera.quaternion,camera.scale);seethruPlane.quaternion.copy(camera.quaternion);var fov=THREE.Math.radToDeg(Math.atan(1/camera.projectionMatrix.elements[5]))*2;
THREEx.ArMarkerCloak.fragmentShader="\n"+" varying vec2 vUv;\n"+" uniform sampler2D texture;\n"+" uniform float opacity;\n"+"\n"+" void main(void){\n"+" vec3 color = texture2D( texture, vUv ).rgb;\n"+"\n"+" gl_FragColor = vec4( color, opacity);\n"+" }";var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkerControls=THREEx.ArMarkerControls=function(context,object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.context=context;this.parameters={size:1,type:"unknown",patternUrl:null,barcodeValue:null,changeMatrixMode:"modelViewMatrix",minConfidence:.6};var possibleValues=["pattern","barcode","unknown"];console.assert(possibleValues.indexOf(this.parameters.type)!==-1,"illegal value",this.parameters.type);var possibleValues=["modelViewMatrix","cameraTransformMatrix"];console.assert(possibleValues.indexOf(this.parameters.changeMatrixMode)!==-1,"illegal value",this.parameters.changeMatrixMode);this.object3d=object3d;this.object3d.matrixAutoUpdate=false;this.object3d.visible=false;setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}context.addMarker(this);if(_this.context.parameters.trackingBackend==="artoolkit"){this._initArtoolkit()}else if(_this.context.parameters.trackingBackend==="aruco"){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)}else if(_this.context.parameters.trackingBackend==="tango"){this._initTango()}else console.assert(false)};ARjs.MarkerControls.prototype=Object.create(THREEx.ArBaseControls.prototype);ARjs.MarkerControls.prototype.constructor=THREEx.ArMarkerControls;ARjs.MarkerControls.prototype.dispose=function(){this.context.removeMarker(this)};ARjs.MarkerControls.prototype.updateWithModelViewMatrix=function(modelViewMatrix){var markerObject3D=this.object3d;markerObject3D.visible=true;if(this.context.parameters.trackingBackend==="artoolkit"){var tmpMatrix=(new THREE.Matrix4).copy(this.context._artoolkitProjectionAxisTransformMatrix);tmpMatrix.multiply(modelViewMatrix);modelViewMatrix.copy(tmpMatrix)}else if(this.context.parameters.trackingBackend==="aruco"){}else if(this.context.parameters.trackingBackend==="tango"){}else console.assert(false);if(this.context.parameters.trackingBackend!=="tango"){var markerAxisTransformMatrix=(new THREE.Matrix4).makeRotationX(Math.PI/2);modelViewMatrix.multiply(markerAxisTransformMatrix)}if(this.parameters.changeMatrixMode==="modelViewMatrix"){markerObject3D.matrix.copy(modelViewMatrix)}else if(this.parameters.changeMatrixMode==="cameraTransformMatrix"){markerObject3D.matrix.getInverse(modelViewMatrix)}else{console.assert(false)}markerObject3D.matrix.decompose(markerObject3D.position,markerObject3D.quaternion,markerObject3D.scale);this.dispatchEvent({type:"markerFound"})};ARjs.MarkerControls.prototype.name=function(){var name="";name+=this.parameters.type;if(this.parameters.type==="pattern"){var url=this.parameters.patternUrl;var basename=url.replace(/^.*\//g,"");name+=" - "+basename}else if(this.parameters.type==="barcode"){name+=" - "+this.parameters.barcodeValue}else{console.assert(false,"no .name() implemented for this marker controls")}return name};ARjs.MarkerControls.prototype._initArtoolkit=function(){var _this=this;var artoolkitMarkerId=null;var delayedInitTimerId=setInterval(function(){var arController=_this.context.arController;if(arController===null)return;clearInterval(delayedInitTimerId);delayedInitTimerId=null;postInit()},1e3/50);return;function postInit(){var arController=_this.context.arController;console.assert(arController!==null);if(_this.parameters.type==="pattern"){arController.loadMarker(_this.parameters.patternUrl,function(markerId){artoolkitMarkerId=markerId;arController.trackPatternMarkerId(artoolkitMarkerId,_this.parameters.size)})}else if(_this.parameters.type==="barcode"){artoolkitMarkerId=_this.parameters.barcodeValue;arController.trackBarcodeMarkerId(artoolkitMarkerId,_this.parameters.size)}else if(_this.parameters.type==="unknown"){artoolkitMarkerId=null}else{console.log(false,"invalid marker type",_this.parameters.type)}arController.addEventListener("getMarker",function(event){if(event.data.type===artoolkit.PATTERN_MARKER&&_this.parameters.type==="pattern"){if(artoolkitMarkerId===null)return;if(event.data.marker.idPatt===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.BARCODE_MARKER&&_this.parameters.type==="barcode"){if(artoolkitMarkerId===null)return;if(event.data.marker.idMatrix===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.UNKNOWN_MARKER&&_this.parameters.type==="unknown"){onMarkerFound(event)}})}function onMarkerFound(event){if(event.data.type===artoolkit.PATTERN_MARKER&&event.data.marker.cfPatt<_this.parameters.minConfidence)return;if(event.data.type===artoolkit.BARCODE_MARKER&&event.data.marker.cfMatt<_this.parameters.minConfidence)return;var modelViewMatrix=(new THREE.Matrix4).fromArray(event.data.matrix);_this.updateWithModelViewMatrix(modelViewMatrix)}};ARjs.MarkerControls.prototype._initAruco=function(){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)};ARjs.MarkerControls.prototype._initTango=function(){var _this=this;console.log("init tango ArMarkerControls")};var THREEx=THREEx||{};THREEx.ArMarkerHelper=function(markerControls){this.object3d=new THREE.Group;var mesh=new THREE.AxisHelper;this.object3d.add(mesh);var text=markerControls.id;var canvas=document.createElement("canvas");canvas.width=64;canvas.height=64;var context=canvas.getContext("2d");var texture=new THREE.CanvasTexture(canvas);context.font="48px monospace";context.fillStyle="rgba(192,192,255, 0.5)";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="darkblue";context.fillText(text,canvas.width/4,3*canvas.height/4);texture.needsUpdate=true;var geometry=new THREE.PlaneGeometry(1,1);var material=new THREE.MeshBasicMaterial({map:texture,transparent:true});var mesh=new THREE.Mesh(geometry,material);mesh.rotation.x=-Math.PI/2;this.object3d.add(mesh)};var THREEx=THREEx||{};THREEx.ArSmoothedControls=function(object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.object3d.visible=false;this._lastLerpStepAt=null;this._visibleStartedAt=null;this._unvisibleStartedAt=null;parameters=parameters||{};this.parameters={lerpPosition:.8,lerpQuaternion:.2,lerpScale:.7,lerpStepDelay:1/60,minVisibleDelay:0,minUnvisibleDelay:.2};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};THREEx.ArSmoothedControls.prototype=Object.create(THREEx.ArBaseControls.prototype);THREEx.ArSmoothedControls.prototype.constructor=THREEx.ArSmoothedControls;THREEx.ArSmoothedControls.prototype.update=function(targetObject3d){var object3d=this.object3d;var parameters=this.parameters;var wasVisible=object3d.visible;var present=performance.now()/1e3;if(targetObject3d.visible===false)this._visibleStartedAt=null;if(targetObject3d.visible===true)this._unvisibleStartedAt=null;if(targetObject3d.visible===true&&this._visibleStartedAt===null)this._visibleStartedAt=present;if(targetObject3d.visible===false&&this._unvisibleStartedAt===null)this._unvisibleStartedAt=present;if(wasVisible===false&&targetObject3d.visible===true){var visibleFor=present-this._visibleStartedAt;if(visibleFor>=this.parameters.minVisibleDelay){object3d.visible=true;snapDirectlyToTarget()}}if(wasVisible===true&&targetObject3d.visible===false){var unvisibleFor=present-this._unvisibleStartedAt;if(unvisibleFor>=this.parameters.minUnvisibleDelay){object3d.visible=false}}if(this._lastLerpStepAt===null){applyOneSlerpStep();this._lastLerpStepAt=present}else{var nStepsToDo=Math.floor((present-this._lastLerpStepAt)/this.parameters.lerpStepDelay);for(var i=0;i<nStepsToDo;i++){applyOneSlerpStep();this._lastLerpStepAt+=this.parameters.lerpStepDelay}}if(false){snapDirectlyToTarget()}this.object3d.updateMatrix();if(wasVisible===false&&object3d.visible===true){this.dispatchEvent({type:"becameVisible"})}if(wasVisible===true&&object3d.visible===false){this.dispatchEvent({type:"becameUnVisible"})}return;function snapDirectlyToTarget(){object3d.position.copy(targetObject3d.position);object3d.quaternion.copy(targetObject3d.quaternion);object3d.scale.copy(targetObject3d.scale)}function applyOneSlerpStep(){object3d.position.lerp(targetObject3d.position,parameters.lerpPosition);object3d.quaternion.slerp(targetObject3d.quaternion,parameters.lerpQuaternion);object3d.scale.lerp(targetObject3d.scale,parameters.lerpScale)}};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Context=THREEx.ArToolkitContext=function(parameters){var _this=this;_this._updatedAt=null;this.parameters={trackingBackend:"artoolkit",debug:false,detectionMode:"mono",matrixCodeType:"3x3",cameraParametersUrl:ARjs.Context.baseURL+"parameters/camera_para.dat",maxDetectionRate:60,canvasWidth:640,canvasHeight:480,patternRatio:.5,imageSmoothingEnabled:false};console.assert(["artoolkit","aruco","tango"].indexOf(this.parameters.trackingBackend)!==-1,"invalid parameter trackingBackend",this.parameters.trackingBackend);console.assert(["color","color_and_matrix","mono","mono_and_matrix"].indexOf(this.parameters.detectionMode)!==-1,"invalid parameter detectionMode",this.parameters.detectionMode);this.arController=null;this.arucoContext=null;_this.initialized=false;this._arMarkersControls=[];setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};Object.assign(ARjs.Context.prototype,THREE.EventDispatcher.prototype);ARjs.Context.baseURL="https://jeromeetienne.github.io/AR.js/three.js/";ARjs.Context.REVISION="1.6.
2
";ARjs.Context.createDefaultCamera=function(trackingBackend){console.assert(false,"use ARjs.Utils.createDefaultCamera instead");if(trackingBackend==="artoolkit"){var camera=new THREE.Camera}else if(trackingBackend==="aruco"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else if(trackingBackend==="tango"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else console.assert(false);return camera};ARjs.Context.prototype.init=function(onCompleted){var _this=this;if(this.parameters.trackingBackend==="artoolkit"){this._initArtoolkit(done)}else if(this.parameters.trackingBackend==="aruco"){this._initAruco(done)}else if(this.parameters.trackingBackend==="tango"){this._initTango(done)}else console.assert(false);return;function done(){_this.dispatchEvent({type:"initialized"});_this.initialized=true;onCompleted&&onCompleted()}};ARjs.Context.prototype.update=function(srcElement){if(this.parameters.trackingBackend==="artoolkit"&&this.arController===null)return false;var present=performance.now();if(this._updatedAt!==null&&present-this._updatedAt<1e3/this.parameters.maxDetectionRate){return false}this._updatedAt=present;this._arMarkersControls.forEach(function(markerControls){markerControls.object3d.visible=false});if(this.parameters.trackingBackend==="artoolkit"){this._updateArtoolkit(srcElement)}else if(this.parameters.trackingBackend==="aruco"){this._updateAruco(srcElement)}else if(this.parameters.trackingBackend==="tango"){this._updateTango(srcElement)}else{console.assert(false)}this.dispatchEvent({type:"sourceProcessed"});return true};ARjs.Context.prototype.addMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);this._arMarkersControls.push(arMarkerControls)};ARjs.Context.prototype.removeMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);var index=this.arMarkerControlss.indexOf(artoolkitMarker);console.assert(index!==index);this._arMarkersControls.splice(index,1)};ARjs.Context.prototype._initArtoolkit=function(onCompleted){var _this=this;this._artoolkitProjectionAxisTransformMatrix=new THREE.Matrix4;this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationY(Math.PI));this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationZ(Math.PI));var cameraParameters=new ARCameraParam(_this.parameters.cameraParametersUrl,function(){var arController=new ARController(_this.parameters.canvasWidth,_this.parameters.canvasHeight,cameraParameters);_this.arController=arController;arController.ctx.mozImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.webkitImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.msImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.imageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;if(_this.parameters.debug===true){arController.debugSetup();arController.canvas.style.position="absolute";arController.canvas.style.top="0px";arController.canvas.style.opacity="0.6";arController.canvas.style.pointerEvents="none";arController.canvas.style.zIndex="-1"}var detectionModes={color:artoolkit.AR_TEMPLATE_MATCHING_COLOR,color_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX,mono:artoolkit.AR_TEMPLATE_MATCHING_MONO,mono_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_MONO_AND_MATRIX};var detectionMode=detectionModes[_this.parameters.detectionMode];console.assert(detectionMode!==undefined);arController.setPatternDetectionMode(detectionMode);var matrixCodeTypes={"3x3":artoolkit.AR_MATRIX_CODE_3x3,"3x3_HAMMING63":artoolkit.AR_MATRIX_CODE_3x3_HAMMING63,"3x3_PARITY65":artoolkit.AR_MATRIX_CODE_3x3_PARITY65,"4x4":artoolkit.AR_MATRIX_CODE_4x4,"4x4_BCH_13_9_3":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_9_3,"4x4_BCH_13_5_5":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_5_5};var matrixCodeType=matrixCodeTypes[_this.parameters.matrixCodeType];console.assert(matrixCodeType!==undefined);arController.setMatrixCodeType(matrixCodeType);arController.setPattRatio(_this.parameters.patternRatio);onCompleted()});return this};ARjs.Context.prototype.getProjectionMatrix=function(srcElement){console.assert(this.parameters.trackingBackend==="artoolkit");console.assert(this.arController,"arController MUST be initialized to call this function");var projectionMatrixArr=this.arController.getCameraMatrix();var projectionMatrix=(new THREE.Matrix4).fromArray(projectionMatrixArr);projectionMatrix.multiply(this._artoolkitProjectionAxisTransformMatrix);return projectionMatrix};ARjs.Context.prototype._updateArtoolkit=function(srcElement){this.arController.process(srcElement)};ARjs.Context.prototype._initAruco=function(onCompleted){this.arucoContext=new THREEx.ArucoContext;this.arucoContext.canvas.width=this.parameters.canvasWidth;this.arucoContext.canvas.height=this.parameters.canvasHeight;var context=this.arucoContext.canvas.getContext("2d");context.webkitImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.msImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.imageSmoothingEnabled=this.parameters.imageSmoothingEnabled;setTimeout(function(){onCompleted()},0)};ARjs.Context.prototype._updateAruco=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var detectedMarkers=this.arucoContext.detect(srcElement);detectedMarkers.forEach(function(detectedMarker){var foundControls=null;for(var i=0;i<arMarkersControls.length;i++){console.assert(arMarkersControls[i].parameters.type==="barcode");if(arMarkersControls[i].parameters.barcodeValue===detectedMarker.id){foundControls=arMarkersControls[i];break}}if(foundControls===null)return;var tmpObject3d=new THREE.Object3D;_this.arucoContext.updateObject3D(tmpObject3d,foundControls._arucoPosit,foundControls.parameters.size,detectedMarker);tmpObject3d.updateMatrix();foundControls.updateWithModelViewMatrix(tmpObject3d.matrix)})};ARjs.Context.prototype._initTango=function(onCompleted){var _this=this;if(navigator.getVRDisplays){}else if(navigator.getVRDevices){alert("Your browser supports WebVR but not the latest version. See <a href='http://webvr.info'>webvr.info</a> for more info.")}else{alert("Your browser does not support WebVR. See <a href='http://webvr.info'>webvr.info</a> for assistance.")}this._tangoContext={vrDisplay:null,vrPointCloud:null,frameData:new VRFrameData};navigator.getVRDisplays().then(function(vrDisplays){if(vrDisplays.length===0)alert("no vrDisplays available");var vrDisplay=_this._tangoContext.vrDisplay=vrDisplays[0];console.log("vrDisplays.displayName :",vrDisplay.displayName);if(vrDisplay.displayName==="Tango VR Device"){_this._tangoContext.vrPointCloud=new THREE.WebAR.VRPointCloud(vrDisplay,true)}onCompleted()})};ARjs.Context.prototype._updateTango=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var tangoContext=this._tangoContext;var vrDisplay=this._tangoContext.vrDisplay;if(vrDisplay===null)return;if(vrDisplay.displayName==="Tango VR Device"){var showPointCloud=true;var pointsToSkip=0;_this._tangoContext.vrPointCloud.update(showPointCloud,pointsToSkip,true)}if(this._arMarkersControls.length===0)return;var foundControls=this._arMarkersControls[0];var frameData=this._tangoContext.frameData;vrDisplay.getFrameData(frameData);if(frameData.pose.position===null)return;if(frameData.pose.orientation===null)return;var position=(new THREE.Vector3).fromArray(frameData.pose.position);var quaternion=(new THREE.Quaternion).fromArray(frameData.pose.orientation);var scale=new THREE.Vector3(1,1,1);var cameraTransformMatrix=(new THREE.Matrix4).compose(position,quaternion,scale);var modelViewMatrix=new THREE.Matrix4;modelViewMatrix.getInverse(cameraTransformMatrix);foundControls.updateWithModelViewMatrix(modelViewMatrix)};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Profile=THREEx.ArToolkitProfile=function(){this.reset();this.performance("default")};ARjs.Profile.prototype._guessPerformanceLabel=function(){var isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/webOS/i)||navigator.userAgent.match(/iPhone/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPod/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Windows Phone/i)?true:false;if(isMobile===true){return"phone-normal"}return"desktop-normal"};ARjs.Profile.prototype.reset=function(){this.sourceParameters={sourceType:"webcam"};this.contextParameters={cameraParametersUrl:THREEx.ArToolkitContext.baseURL+"../data/data/camera_para.dat",detectionMode:"mono"};this.defaultMarkerParameters={type:"pattern",patternUrl:THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro",changeMatrixMode:"modelViewMatrix"};return this};ARjs.Profile.prototype.performance=function(label){if(label==="default"){label=this._guessPerformanceLabel()}if(label==="desktop-fast"){this.contextParameters.canvasWidth=640*3;this.contextParameters.canvasHeight=480*3;this.contextParameters.maxDetectionRate=30}else if(label==="desktop-normal"){this.contextParameters.canvasWidth=640;this.contextParameters.canvasHeight=480;this.contextParameters.maxDetectionRate=60}else if(label==="phone-normal"){this.contextParameters.canvasWidth=80*4;this.contextParameters.canvasHeight=60*4;this.contextParameters.maxDetectionRate=30}else if(label==="phone-slow"){this.contextParameters.canvasWidth=80*3;this.contextParameters.canvasHeight=60*3;this.contextParameters.maxDetectionRate=30}else{console.assert(false,"unknonwn label "+label)}return this};ARjs.Profile.prototype.defaultMarker=function(trackingBackend){trackingBackend=trackingBackend||this.contextParameters.trackingBackend;if(trackingBackend==="artoolkit"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="pattern";this.defaultMarkerParameters.patternUrl=THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro"}else if(trackingBackend==="aruco"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else if(trackingBackend==="tango"){this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else console.assert(false);return this};ARjs.Profile.prototype.sourceWebcam=function(){this.sourceParameters.sourceType="webcam";delete this.sourceParameters.sourceUrl;return this};ARjs.Profile.prototype.sourceVideo=function(url){this.sourceParameters.sourceType="video";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.sourceImage=function(url){this.sourceParameters.sourceType="image";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.trackingBackend=function(trackingBackend){console.warn("stop profile.trackingBackend() obsolete function. use .trackingMethod instead");this.contextParameters.trackingBackend=trackingBackend;return this};ARjs.Profile.prototype.changeMatrixMode=function(changeMatrixMode){this.defaultMarkerParameters.changeMatrixMode=changeMatrixMode;return this};ARjs.Profile.prototype.trackingMethod=function(trackingMethod){var data=ARjs.Utils.parseTrackingMethod(trackingMethod);this.defaultMarkerParameters.markersAreaEnabled=data.markersAreaEnabled;this.contextParameters.trackingBackend=data.trackingBackend;return this};ARjs.Profile.prototype.checkIfValid=function(){if(this.contextParameters.trackingBackend==="tango"){this.sourceImage(THREEx.ArToolkitContext.baseURL+"../data/images/img.jpg")}return this};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Source=THREEx.ArToolkitSource=function(parameters){var _this=this;this.ready=false;this.domElement=null;this.parameters={sourceType:"webcam",sourceUrl:null,deviceId:null,sourceWidth:640,sourceHeight:480,displayWidth:640,displayHeight:480};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};ARjs.Source.prototype.init=function(onReady,onError){var _this=this;if(this.parameters.sourceType==="image"){var domElement=this._initSourceImage(onSourceReady,onError)}else if(this.parameters.sourceType==="video"){var domElement=this._initSourceVideo(onSourceReady,onError)}else if(this.parameters.sourceType==="webcam"){var domElement=this._initSourceWebcam(onSourceReady,onError)}else{console.assert(false)}this.domElement=domElement;this.domElement.style.position="absolute";this.domElement.style.top="0px";this.domElement.style.left="0px";this.domElement.style.zIndex="-2";return this;function onSourceReady(){document.body.appendChild(_this.domElement);_this.ready=true;onReady&&onReady()}};ARjs.Source.prototype._initSourceImage=function(onReady){var domElement=document.createElement("img");domElement.src=this.parameters.sourceUrl;domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.naturalWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceVideo=function(onReady){var domElement=document.createElement("video");domElement.src=this.parameters.sourceUrl;domElement.style.objectFit="initial";domElement.autoplay=true;domElement.webkitPlaysinline=true;domElement.controls=false;domElement.loop=true;domElement.muted=true;document.body.addEventListener("click",function onClick(){document.body.removeEventListener("click",onClick);domElement.play()});domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceWebcam=function(onReady,onError){var _this=this;onError=onError||function(error){alert("Webcam Error\nName: "+error.name+"\nMessage: "+error.message)};var domElement=document.createElement("video");domElement.setAttribute("autoplay","");domElement.setAttribute("muted","");domElement.setAttribute("playsinline","");domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";if(navigator.mediaDevices===undefined||navigator.mediaDevices.enumerateDevices===undefined||navigator.mediaDevices.getUserMedia===undefined){if(navigator.mediaDevices===undefined)var fctName="navigator.mediaDevices";else if(navigator.mediaDevices.enumerateDevices===undefined)var fctName="navigator.mediaDevices.enumerateDevices";else if(navigator.mediaDevices.getUserMedia===undefined)var fctName="navigator.mediaDevices.getUserMedia";else console.assert(false);onError({name:"",message:"WebRTC issue-! "+fctName+" not present in your browser"});return null}navigator.mediaDevices.enumerateDevices().then(function(devices){var userMediaConstraints={audio:false,video:{facingMode:"environment",width:{ideal:_this.parameters.sourceWidth},height:{ideal:_this.parameters.sourceHeight}}};if(null!==_this.parameters.deviceId){userMediaConstraints.video.deviceId={exact:_this.parameters.deviceId}}navigator.mediaDevices.getUserMedia(userMediaConstraints).then(function success(stream){domElement.srcObject=stream;document.body.addEventListener("click",function(){domElement.play()});var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50)}).catch(function(error){onError({name:error.name,message:error.message})})}).catch(function(error){onError({message:error.message})});return domElement};ARjs.Source.prototype.hasMobileTorch=function(){var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false)return false;if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];if(videoTrack.getCapabilities===undefined)return false;var capabilities=videoTrack.getCapabilities();return capabilities.torch?true:false};ARjs.Source.prototype.toggleMobileTorch=function(){console.assert(this.hasMobileTorch()===true);var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false){alert("enabling mobile torch is available only on webcam");return}if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];var capabilities=videoTrack.getCapabilities();if(!capabilities.torch){alert("no mobile torch is available on your camera");return}this._currentTorchStatus=this._currentTorchStatus===false?true:false;videoTrack.applyConstraints({advanced:[{torch:this._currentTorchStatus}]}).catch(function(error){console.log(error)})};ARjs.Source.prototype.domElementWidth=function(){return parseInt(this.domElement.style.width)};ARjs.Source.prototype.domElementHeight=function(){return parseInt(this.domElement.style.height)};ARjs.Source.prototype.onResizeElement=function(){var _this=this;var screenWidth=window.innerWidth;var screenHeight=window.innerHeight;console.assert(arguments.length===0);if(this.domElement.nodeName==="IMG"){var sourceWidth=this.domElement.naturalWidth;var sourceHeight=this.domElement.naturalHeight}else if(this.domElement.nodeName==="VIDEO"){var sourceWidth=this.domElement.videoWidth;var sourceHeight=this.domElement.videoHeight}else{console.assert(false)}var sourceAspect=sourceWidth/sourceHeight;var screenAspect=screenWidth/screenHeight;if(screenAspect<sourceAspect){var newWidth=sourceAspect*screenHeight;this.domElement.style.width=newWidth+"px";this.domElement.style.marginLeft=-(newWidth-screenWidth)/2+"px";this.domElement.style.height=screenHeight+"px";this.domElement.style.marginTop="0px"}else{var newHeight=1/(sourceAspect/screenWidth);this.domElement.style.height=newHeight+"px";this.domElement.style.marginTop=-(newHeight-screenHeight)/2+"px";this.domElement.style.width=screenWidth+"px";this.domElement.style.marginLeft="0px"}};ARjs.Source.prototype.copyElementSizeTo=function(otherElement){if(window.innerWidth>window.innerHeight){otherElement.style.width=this.domElement.style.width;otherElement.style.height=this.domElement.style.height;otherElement.style.marginLeft=this.domElement.style.marginLeft;otherElement.style.marginTop=this.domElement.style.marginTop}else{otherElement.style.height=this.domElement.style.height;otherElement.style.width=parseInt(otherElement.style.height)*4/3+"px";otherElement.style.marginLeft=(window.innerWidth-parseInt(otherElement.style.width))/2+"px";otherElement.style.marginTop=0}};ARjs.Source.prototype.copySizeTo=function(){console.warn("obsolete function arToolkitSource.copySizeTo. Use arToolkitSource.copyElementSizeTo");this.copyElementSizeTo.apply(this,arguments)};ARjs.Source.prototype.onResize=function(arToolkitContext,renderer,camera){if(arguments.length!==3){console.warn("obsolete function arToolkitSource.onResize. Use arToolkitSource.onResizeElement");return this.onResizeElement.apply(this,arguments)}var trackingBackend=arToolkitContext.parameters.trackingBackend;if(trackingBackend==="artoolkit"){this.onResizeElement();var isAframe=renderer.domElement.dataset.aframeCanvas?true:false;if(isAframe===false){this.copyElementSizeTo(renderer.domElement)}else{}if(arToolkitContext.arController!==null){this.copyElementSizeTo(arToolkitContext.arController.canvas)}}else if(trackingBackend==="aruco"){this.onResizeElement();this.copyElementSizeTo(renderer.domElement);this.copyElementSizeTo(arToolkitContext.arucoContext.canvas)}else if(trackingBackend==="tango"){renderer.setSize(window.innerWidth,window.innerHeight)}else console.assert(false,"unhandled trackingBackend "+trackingBackend);if(trackingBackend==="artoolkit"){if(arToolkitContext.arController!==null){camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix())}}else if(trackingBackend==="aruco"){camera.aspect=renderer.domElement.width/renderer.domElement.height;camera.updateProjectionMatrix()}else if(trackingBackend==="tango"){var vrDisplay=arToolkitContext._tangoContext.vrDisplay;if(vrDisplay&&vrDisplay.displayName==="Tango VR Device")THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay,camera)}else console.assert(false,"unhandled trackingBackend "+trackingBackend)};var THREEx=THREEx||{};THREEx.ArVideoInWebgl=function(videoTexture){var _this=this;var geometry=new THREE.PlaneGeometry(2,2);var material=new THREE.MeshBasicMaterial({map:videoTexture});var seethruPlane=new THREE.Mesh(geometry,material);this.object3d=seethruPlane;this.update=function(camera){camera.updateMatrixWorld(true);var position=new THREE.Vector3(-0,0,-20);var position=new THREE.Vector3(-0,0,-20);seethruPlane.position.copy(position);camera.localToWorld(seethruPlane.position);camera.matrixWorld.decompose(camera.position,camera.quaternion,camera.scale);seethruPlane.quaternion.copy(camera.quaternion);var fov=THREE.Math.radToDeg(Math.atan(1/camera.projectionMatrix.elements[5]))*2;
var elementWidth=parseFloat(arToolkitSource.domElement.style.width.replace(/px$/,""),10);var elementHeight=parseFloat(arToolkitSource.domElement.style.height.replace(/px$/,""),10);var aspect=elementWidth/elementHeight;seethruPlane.scale.y=Math.tan(THREE.Math.DEG2RAD*fov/2)*position.length();seethruPlane.scale.x=seethruPlane.scale.y*aspect}};var THREEx=THREEx||{};THREEx.HitTestingPlane=function(sourceElement){this._sourceElement=sourceElement;this._pickingScene=new THREE.Scene;var geometry=new THREE.PlaneGeometry(20,20,19,19).rotateX(-Math.PI/2);var material=new THREE.MeshBasicMaterial({wireframe:true});this._pickingPlane=new THREE.Mesh(geometry,material);this._pickingScene.add(this._pickingPlane);var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);this._pickingCamera=new THREE.PerspectiveCamera(42,fullWidth/fullHeight,.1,30)};THREEx.HitTestingPlane.prototype.update=function(camera,pickingRoot,changeMatrixMode){this.onResize();if(changeMatrixMode==="modelViewMatrix"){var pickingPlane=this._pickingPlane;pickingRoot.parent.updateMatrixWorld();pickingPlane.matrix.copy(pickingRoot.parent.matrixWorld);pickingPlane.matrix.decompose(pickingPlane.position,pickingPlane.quaternion,pickingPlane.scale)}else if(changeMatrixMode==="cameraTransformMatrix"){var pickingCamera=this._pickingCamera;camera.updateMatrixWorld();pickingCamera.matrix.copy(camera.matrixWorld);pickingCamera.matrix.decompose(pickingCamera.position,pickingCamera.quaternion,pickingCamera.scale)}else console.assert(false)};THREEx.HitTestingPlane.prototype.onResize=function(){var sourceElement=this._sourceElement;var pickingCamera=this._pickingCamera;var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);pickingCamera.aspect=fullWidth/fullHeight;pickingCamera.updateProjectionMatrix()};THREEx.HitTestingPlane.prototype.test=function(mouseX,mouseY){mouseX=(mouseX-.5)*2;mouseY=-(mouseY-.5)*2;this._pickingScene.updateMatrixWorld(true);var raycaster=new THREE.Raycaster;var mouseVector3=new THREE.Vector3(mouseX,mouseY,1);raycaster.setFromCamera(mouseVector3,this._pickingCamera);var intersects=raycaster.intersectObjects([this._pickingPlane]);if(intersects.length===0)return null;var position=this._pickingPlane.worldToLocal(intersects[0].point.clone());var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3(1,1,1);return{position:position,quaternion:quaternion,scale:scale}};THREEx.HitTestingPlane.prototype.renderDebug=function(renderer){renderer.render(this._pickingScene,this._pickingCamera)};var THREEx=THREEx||{};THREEx.HitTestingTango=function(arContext){this._arContext=arContext;this.boundingSphereRadius=.01;this.resultScale=new THREE.Vector3(1,1,1).multiplyScalar(1)};THREEx.HitTestingTango.prototype.update=function(){};THREEx.HitTestingTango.prototype.test=function(mouseX,mouseY){var vrDisplay=this._arContext._tangoContext.vrDisplay;if(vrDisplay===null)return null;if(vrDisplay.displayName!=="Tango VR Device")return null;var pointAndPlane=vrDisplay.getPickingPointAndPlaneInPointCloud(mouseX,mouseY);if(pointAndPlane==null){console.warn("Could not retrieve the correct point and plane.");return null}var boundingSphereRadius=.01;var object3d=new THREE.Object3D;THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud(pointAndPlane,object3d,this.boundingSphereRadius);object3d.rotateZ(-Math.PI/2);var result={position:object3d.position,quaternion:object3d.quaternion,scale:this.resultScale};return result};var ARjs=ARjs||{};ARjs.Anchor=function(arSession,markerParameters){var _this=this;var arContext=arSession.arContext;var scene=arSession.parameters.scene;var camera=arSession.parameters.camera;this.arSession=arSession;this.parameters=markerParameters;console.log("ARjs.Anchor -","changeMatrixMode:",this.parameters.changeMatrixMode,"/ markersAreaEnabled:",markerParameters.markersAreaEnabled);var markerRoot=new THREE.Group;scene.add(markerRoot);if(markerParameters.changeMatrixMode==="modelViewMatrix"){var controlledObject=markerRoot}else if(markerParameters.changeMatrixMode==="cameraTransformMatrix"){var controlledObject=camera}else console.assert(false);if(markerParameters.markersAreaEnabled===false){var markerControls=new THREEx.ArMarkerControls(arContext,controlledObject,markerParameters);this.controls=markerControls}else{console.assert(arContext.parameters.trackingBackend==="artoolkit"||arContext.parameters.trackingBackend==="aruco");if(location.hash.substring(1).startsWith("markers-page-resolution=")===true){var markerPageResolution=location.hash.substring(1);var matches=markerPageResolution.match(/markers-page-resolution=(\d+)x(\d+)/);console.assert(matches.length===3);var resolutionW=parseInt(matches[1]);var resolutionH=parseInt(matches[2]);var arContext=arSession.arContext;ARjs.MarkersAreaUtils.storeMarkersAreaFileFromResolution(arContext.parameters.trackingBackend,resolutionW,resolutionH)}if(localStorage.getItem("ARjsMultiMarkerFile")===null){ARjs.MarkersAreaUtils.storeDefaultMultiMarkerFile(arContext.parameters.trackingBackend)}console.assert(localStorage.getItem("ARjsMultiMarkerFile")!==null);var multiMarkerFile=localStorage.getItem("ARjsMultiMarkerFile");if(markerParameters.changeMatrixMode==="modelViewMatrix"){var parent3D=scene}else if(markerParameters.changeMatrixMode==="cameraTransformMatrix"){var parent3D=camera}else console.assert(false);var multiMarkerControls=ARjs.MarkersAreaControls.fromJSON(arContext,parent3D,controlledObject,multiMarkerFile);this.controls=multiMarkerControls;multiMarkerControls.parameters.changeMatrixMode=markerParameters.changeMatrixMode;var markerHelpers=[];multiMarkerControls.subMarkersControls.forEach(function(subMarkerControls){var markerHelper=new THREEx.ArMarkerHelper(subMarkerControls);markerHelper.object3d.visible=false;subMarkerControls.object3d.add(markerHelper.object3d);markerHelpers.push(markerHelper)});this.markersArea={};this.markersArea.setSubMarkersVisibility=function(visible){markerHelpers.forEach(function(markerHelper){markerHelper.object3d.visible=visible})}}this.object3d=new THREE.Group;var shouldBeSmoothed=true;if(arContext.parameters.trackingBackend==="tango")shouldBeSmoothed=false;if(shouldBeSmoothed===true){var smoothedRoot=new THREE.Group;scene.add(smoothedRoot);var smoothedControls=new THREEx.ArSmoothedControls(smoothedRoot);smoothedRoot.add(this.object3d)}else{markerRoot.add(this.object3d)}this.update=function(){_this.object3d.visible=_this.object3d.parent.visible;if(smoothedControls!==undefined){if(multiMarkerControls!==undefined){multiMarkerControls.updateSmoothedControls(smoothedControls)}smoothedControls.update(markerRoot)}}};var ARjs=ARjs||{};ARjs.SessionDebugUI=function(arSession,tangoPointCloud){var trackingBackend=arSession.arContext.parameters.trackingBackend;this.domElement=document.createElement("div");this.domElement.style.color="rgba(0,0,0,0.9)";this.domElement.style.backgroundColor="rgba(127,127,127,0.5)";this.domElement.style.display="inline-block";this.domElement.style.padding="0.5em";this.domElement.style.margin="0.5em";this.domElement.style.textAlign="left";var domElement=document.createElement("span");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.innerHTML="<b>trackingBackend</b> : "+trackingBackend;if(ARjs.SessionDebugUI.AugmentedWebsiteURL){var domElement=document.createElement("a");domElement.innerHTML="Share on augmented-websites";domElement.style.display="block";domElement.href=ARjs.SessionDebugUI.AugmentedWebsiteURL+"?"+location.href;this.domElement.appendChild(domElement)}if(trackingBackend==="tango"&&tangoPointCloud){var domElement=document.createElement("button");this.domElement.appendChild(domElement);domElement.id="buttonTangoTogglePointCloud";domElement.innerHTML="toggle-point-cloud";domElement.href="javascript:void(0)";domElement.addEventListener("click",function(){var scene=arSession.parameters.scene;if(tangoPointCloud.object3d.parent){scene.remove(tangoPointCloud.object3d)}else{scene.add(tangoPointCloud.object3d)}})}};ARjs.SessionDebugUI.AugmentedWebsiteURL="https://webxr.io/augmented-website";ARjs.AnchorDebugUI=function(arAnchor){var _this=this;var arSession=arAnchor.arSession;var trackingBackend=arSession.arContext.parameters.trackingBackend;this.domElement=document.createElement("div");this.domElement.style.color="rgba(0,0,0,0.9)";this.domElement.style.backgroundColor="rgba(127,127,127,0.5)";this.domElement.style.display="inline-block";this.domElement.style.padding="0.5em";this.domElement.style.margin="0.5em";this.domElement.style.textAlign="left";var domElement=document.createElement("span");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.innerHTML="<b>markersAreaEnabled</b> :"+arAnchor.parameters.markersAreaEnabled;if(arAnchor.parameters.markersAreaEnabled){var domElement=document.createElement("button");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.id="buttonToggleMarkerHelpers";domElement.innerHTML="toggle-marker-helper";domElement.href="javascript:void(0)";var subMarkerHelpersVisible=false;domElement.addEventListener("click",function(){subMarkerHelpersVisible=subMarkerHelpersVisible?false:true;arAnchor.markersArea.setSubMarkersVisibility(subMarkerHelpersVisible)})}if(arAnchor.parameters.markersAreaEnabled){var domElement=document.createElement("button");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.id="buttonMarkersAreaLearner";domElement.innerHTML="Learn-new-marker-area";domElement.href="javascript:void(0)";domElement.addEventListener("click",function(){if(ARjs.AnchorDebugUI.MarkersAreaLearnerURL!==null){var learnerURL=ARjs.AnchorDebugUI.MarkersAreaLearnerURL}else{var learnerURL=ARjs.Context.baseURL+"examples/multi-markers/examples/learner.html"}ARjs.MarkersAreaUtils.navigateToLearnerPage(learnerURL,trackingBackend)})}if(arAnchor.parameters.markersAreaEnabled){var domElement=document.createElement("button");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.id="buttonMarkersAreaReset";domElement.innerHTML="Reset-marker-area";domElement.href="javascript:void(0)";domElement.addEventListener("click",function(){ARjs.MarkersAreaUtils.storeDefaultMultiMarkerFile(trackingBackend);location.reload()})}};ARjs.AnchorDebugUI.MarkersAreaLearnerURL=null;var ARjs=ARjs||{};ARjs.HitTesting=function(arSession){var _this=this;var arContext=arSession.arContext;var trackingBackend=arContext.parameters.trackingBackend;this.enabled=true;this._arSession=arSession;this._hitTestingPlane=null;this._hitTestingTango=null;if(trackingBackend==="tango"){_this._hitTestingTango=new THREEx.HitTestingTango(arContext)}else{_this._hitTestingPlane=new THREEx.HitTestingPlane(arSession.arSource.domElement)}};ARjs.HitTesting.prototype.update=function(camera,pickingRoot,changeMatrixMode){if(this.enabled===false)return;if(this._hitTestingTango!==null){this._hitTestingTango.update()}else if(this._hitTestingPlane!==null){this._hitTestingPlane.update(camera,pickingRoot,changeMatrixMode)}else console.assert(false)};ARjs.HitTesting.prototype.testDomEvent=function(domEvent){var trackingBackend=this._arSession.arContext.parameters.trackingBackend;var arSource=this._arSession.arSource;if(this.enabled===false)return[];if(trackingBackend==="tango"){var mouseX=domEvent.pageX/window.innerWidth;var mouseY=domEvent.pageY/window.innerHeight}else{var mouseX=domEvent.clientX/arSource.domElementWidth();var mouseY=domEvent.clientY/arSource.domElementHeight()}return this.test(mouseX,mouseY)};ARjs.HitTesting.prototype.test=function(mouseX,mouseY){var arContext=this._arSession.arContext;var trackingBackend=arContext.parameters.trackingBackend;var hitTestResults=[];if(this.enabled===false)return[];var result=null;if(trackingBackend==="tango"){var result=this._hitTestingTango.test(mouseX,mouseY)}else{var result=this._hitTestingPlane.test(mouseX,mouseY)}if(result===null)return hitTestResults;var hitTestResult=new ARjs.HitTesting.Result(result.position,result.quaternion,result.scale);hitTestResults.push(hitTestResult);return hitTestResults};ARjs.HitTesting.Result=function(position,quaternion,scale){this.position=position;this.quaternion=quaternion;this.scale=scale};ARjs.HitTesting.Result.prototype.apply=function(object3d){object3d.position.copy(this.position);object3d.quaternion.copy(this.quaternion);object3d.scale.copy(this.scale);object3d.updateMatrix()};ARjs.HitTesting.Result.prototype.applyPosition=function(object3d){object3d.position.copy(this.position);object3d.updateMatrix();return this};ARjs.HitTesting.Result.prototype.applyQuaternion=function(object3d){object3d.quaternion.copy(this.quaternion);object3d.updateMatrix();return this};var ARjs=ARjs||{};ARjs.Session=function(parameters){var _this=this;this.parameters={renderer:null,camera:null,scene:null,sourceParameters:{},contextParameters:{}};this.signals={sourceReady:new signals.Signal,contextInitialized:new signals.Signal};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.Session: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.Session: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}console.assert(this.parameters.renderer instanceof THREE.WebGLRenderer);console.assert(this.parameters.camera instanceof THREE.Camera);console.assert(this.parameters.scene instanceof THREE.Scene);Object.defineProperty(this,"renderer",{get:function(){console.warn("use .parameters.renderer renderer");return this.parameters.renderer}});Object.defineProperty(this,"camera",{get:function(){console.warn("use .parameters.camera instead");return this.parameters.camera}});Object.defineProperty(this,"scene",{get:function(){console.warn("use .parameters.scene instead");return this.parameters.scene}});console.log("AR.js",ARjs.Context.REVISION,"- trackingBackend:",parameters.contextParameters.trackingBackend);var arSource=_this.arSource=new ARjs.Source(parameters.sourceParameters);arSource.init(function onReady(){arSource.onResize(arContext,_this.parameters.renderer,_this.parameters.camera);_this.signals.sourceReady.dispatch()});window.addEventListener("resize",function(){arSource.onResize(arContext,_this.parameters.renderer,_this.parameters.camera)});var arContext=_this.arContext=new ARjs.Context(parameters.contextParameters);_this.arContext.init();arContext.addEventListener("initialized",function(event){arSource.onResize(arContext,_this.parameters.renderer,_this.parameters.camera);_this.signals.contextInitialized.dispatch()});this.update=function(){if(arSource.ready===false)return;arContext.update(arSource.domElement)}};ARjs.Session.prototype.onResize=function(){this.arSource.onResize(this.arContext,this.parameters.renderer,this.parameters.camera)};var ARjs=ARjs||{};ARjs.TangoPointCloud=function(arSession){var _this=this;var arContext=arSession.arContext;this.object3d=new THREE.Group;console.warn("Work only on cameraTransformMatrix - fix me - useless limitation");arContext.addEventListener("initialized",function(event){var vrPointCloud=arContext._tangoContext.vrPointCloud;var geometry=vrPointCloud.getBufferGeometry();var material=new THREE.PointsMaterial({size:.01,depthWrite:false});var pointsObject=new THREE.Points(geometry,material);pointsObject.frustumCulled=false;pointsObject.renderDepth=0;_this.object3d.add(pointsObject)})};var ARjs=ARjs||{};ARjs.TangoVideoMesh=function(arSession){var arContext=arSession.arContext;var renderer=arSession.renderer;var videoMesh=null;var vrDisplay=null;var sceneOrtho=new THREE.Scene;var cameraOrtho=new THREE.OrthographicCamera(-1,1,1,-1,0,100);this._sceneOrtho=sceneOrtho;this._cameraOrtho=cameraOrtho;arContext.addEventListener("initialized",function(event){console.assert(arContext.parameters.trackingBackend==="tango");vrDisplay=arContext._tangoContext.vrDisplay;console.assert(vrDisplay,"vrDisplay MUST be defined");if(vrDisplay.displayName!=="Tango VR Device")return;videoMesh=THREE.WebAR.createVRSeeThroughCameraMesh(vrDisplay);sceneOrtho.add(videoMesh)});this.update=function(){console.assert(arContext.parameters.trackingBackend==="tango");if(videoMesh===null)return;THREE.WebAR.updateCameraMeshOrientation(vrDisplay,videoMesh)};this.render=function(){console.assert(arContext.parameters.trackingBackend==="tango");renderer.render(sceneOrtho,cameraOrtho);renderer.clearDepth()}};var ARjs=ARjs||{};ARjs.Utils={};ARjs.Utils.createDefaultCamera=function(trackingMethod){var trackingBackend=this.parseTrackingMethod(trackingMethod).trackingBackend;if(trackingBackend==="artoolkit"){var camera=new THREE.Camera}else if(trackingBackend==="aruco"){var camera=new THREE.PerspectiveCamera(42,window.innerWidth/window.innerHeight,.01,100)}else if(trackingBackend==="tango"){var camera=new THREE.PerspectiveCamera(42,window.innerWidth/window.innerHeight,.01,100)}else console.assert(false,"unknown trackingBackend: "+trackingBackend);return camera};ARjs.Utils.isTango=function(){var isTango=navigator.userAgent.match("Chrome/57.0.2987.5")!==null?true:false;return isTango};ARjs.Utils.parseTrackingMethod=function(trackingMethod){if(trackingMethod==="best"){trackingMethod=ARjs.Utils.isTango()?"tango":"area-artoolkit"}if(trackingMethod.startsWith("area-")){return{trackingBackend:trackingMethod.replace("area-",""),markersAreaEnabled:true}}else{return{trackingBackend:trackingMethod,markersAreaEnabled:false}}};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkersAreaControls=THREEx.ArMultiMarkerControls=function(arToolkitContext,object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);if(arguments.length>3)console.assert("wrong api for",THREEx.ArMultiMarkerControls);this.parameters={subMarkersControls:parameters.subMarkersControls,subMarkerPoses:parameters.subMarkerPoses,changeMatrixMode:parameters.changeMatrixMode!==undefined?parameters.changeMatrixMode:"modelViewMatrix"};this.object3d.visible=false;this.subMarkersControls=this.parameters.subMarkersControls;this.subMarkerPoses=this.parameters.subMarkerPoses;arToolkitContext.addEventListener("sourceProcessed",function(){_this._onSourceProcessed()})};ARjs.MarkersAreaControls.prototype=Object.create(THREEx.ArBaseControls.prototype);ARjs.MarkersAreaControls.prototype.constructor=ARjs.MarkersAreaControls;ARjs.MarkersAreaControls.prototype._onSourceProcessed=function(){var _this=this;var stats={count:0,position:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)},quaternion:{sum:new THREE.Quaternion(0,0,0,0),average:new THREE.Quaternion(0,0,0,0)},scale:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)}};var firstQuaternion=_this.parameters.subMarkersControls[0].object3d.quaternion;this.parameters.subMarkersControls.forEach(function(markerControls,markerIndex){var markerObject3d=markerControls.object3d;if(markerObject3d.visible===false)return;var matrix=markerObject3d.matrix.clone();var markerPose=_this.parameters.subMarkerPoses[markerIndex];matrix.multiply((new THREE.Matrix4).getInverse(markerPose));var position=new THREE.Vector3;var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3;matrix.decompose(position,quaternion,scale);stats.count++;ARjs.MarkersAreaControls.averageVector3(stats.position.sum,position,stats.count,stats.position.average);ARjs.MarkersAreaControls.averageQuaternion(stats.quaternion.sum,quaternion,firstQuaternion,stats.count,stats.quaternion.average);ARjs.MarkersAreaControls.averageVector3(stats.scale.sum,scale,stats.count,stats.scale.average)});if(stats.count>0){_this.object3d.visible=true}else{_this.object3d.visible=false}if(stats.count>0){var modelViewMatrix=new THREE.Matrix4;modelViewMatrix.compose(stats.position.average,stats.quaternion.average,stats.scale.average);if(this.parameters.changeMatrixMode==="modelViewMatrix"){_this.object3d.matrix.copy(modelViewMatrix)}else if(this.parameters.changeMatrixMode==="cameraTransformMatrix"){_this.object3d.matrix.getInverse(modelViewMatrix)}else{console.assert(false)}_this.object3d.matrix.decompose(_this.object3d.position,_this.object3d.quaternion,_this.object3d.scale)}};ARjs.MarkersAreaControls.averageQuaternion=function(quaternionSum,newQuaternion,firstQuaternion,count,quaternionAverage){quaternionAverage=quaternionAverage||new THREE.Quaternion;console.assert(firstQuaternion instanceof THREE.Quaternion===true);if(newQuaternion.dot(firstQuaternion)>0){newQuaternion=new THREE.Quaternion(-newQuaternion.x,-newQuaternion.y,-newQuaternion.z,-newQuaternion.w)}quaternionSum.x+=newQuaternion.x;quaternionSum.y+=newQuaternion.y;quaternionSum.z+=newQuaternion.z;quaternionSum.w+=newQuaternion.w;quaternionAverage.x=quaternionSum.x/count;quaternionAverage.y=quaternionSum.y/count;quaternionAverage.z=quaternionSum.z/count;quaternionAverage.w=quaternionSum.w/count;quaternionAverage.normalize();return quaternionAverage};ARjs.MarkersAreaControls.averageVector3=function(vector3Sum,vector3,count,vector3Average){vector3Average=vector3Average||new THREE.Vector3;vector3Sum.x+=vector3.x;vector3Sum.y+=vector3.y;vector3Sum.z+=vector3.z;vector3Average.x=vector3Sum.x/count;vector3Average.y=vector3Sum.y/count;vector3Average.z=vector3Sum.z/count;return vector3Average};ARjs.MarkersAreaControls.computeCenter=function(jsonData){var multiMarkerFile=JSON.parse(jsonData);var stats={count:0,position:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)},quaternion:{sum:new THREE.Quaternion(0,0,0,0),average:new THREE.Quaternion(0,0,0,0)},scale:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)}};var firstQuaternion=new THREE.Quaternion;multiMarkerFile.subMarkersControls.forEach(function(item){var poseMatrix=(new THREE.Matrix4).fromArray(item.poseMatrix);var position=new THREE.Vector3;var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3;poseMatrix.decompose(position,quaternion,scale);stats.count++;ARjs.MarkersAreaControls.averageVector3(stats.position.sum,position,stats.count,stats.position.average);ARjs.MarkersAreaControls.averageQuaternion(stats.quaternion.sum,quaternion,firstQuaternion,stats.count,stats.quaternion.average);ARjs.MarkersAreaControls.averageVector3(stats.scale.sum,scale,stats.count,stats.scale.average)});var averageMatrix=new THREE.Matrix4;averageMatrix.compose(stats.position.average,stats.quaternion.average,stats.scale.average);return averageMatrix};ARjs.MarkersAreaControls.computeBoundingBox=function(jsonData){var multiMarkerFile=JSON.parse(jsonData);var boundingBox=new THREE.Box3;multiMarkerFile.subMarkersControls.forEach(function(item){var poseMatrix=(new THREE.Matrix4).fromArray(item.poseMatrix);var position=new THREE.Vector3;var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3;poseMatrix.decompose(position,quaternion,scale);boundingBox.expandByPoint(position)});return boundingBox};ARjs.MarkersAreaControls.prototype.updateSmoothedControls=function(smoothedControls,lerpsValues){if(lerpsValues===undefined){lerpsValues=[[.3+.1,.1,.3],[.4+.1,.1,.4],[.4+.1,.2,.5],[.5+.1,.2,.7],[.5+.1,.2,.7]]}var nVisible=0;this.parameters.subMarkersControls.forEach(function(markerControls,markerIndex){var markerObject3d=markerControls.object3d;if(markerObject3d.visible===true)nVisible++});if(lerpsValues[nVisible-1]!==undefined){var lerpValues=lerpsValues[nVisible-1]}else{var lerpValues=lerpsValues[lerpsValues.length-1]}smoothedControls.parameters.lerpPosition=lerpValues[0];smoothedControls.parameters.lerpQuaternion=lerpValues[1];smoothedControls.parameters.lerpScale=lerpValues[2]};ARjs.MarkersAreaControls.fromJSON=function(arToolkitContext,parent3D,markerRoot,jsonData,parameters){var multiMarkerFile=JSON.parse(jsonData);var subMarkersControls=[];var subMarkerPoses=[];parameters=parameters||{};multiMarkerFile.subMarkersControls.forEach(function(item){var markerRoot=new THREE.Object3D;parent3D.add(markerRoot);var subMarkerControls=new THREEx.ArMarkerControls(arToolkitContext,markerRoot,item.parameters);subMarkersControls.push(subMarkerControls);subMarkerPoses.push((new THREE.Matrix4).fromArray(item.poseMatrix))});parameters.subMarkersControls=subMarkersControls;parameters.subMarkerPoses=subMarkerPoses;var multiMarkerControls=new THREEx.ArMultiMarkerControls(arToolkitContext,markerRoot,parameters);return multiMarkerControls};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkersAreaLearning=THREEx.ArMultiMakersLearning=function(arToolkitContext,subMarkersControls){var _this=this;this._arToolkitContext=arToolkitContext;this.subMarkersControls=subMarkersControls;this.enabled=true;arToolkitContext.addEventListener("sourceProcessed",function(){_this._onSourceProcessed()})};ARjs.MarkersAreaLearning.prototype._onSourceProcessed=function(){var originQuaternion=this.subMarkersControls[0].object3d.quaternion;if(this.enabled===false)return;var visibleMarkerControls=this.subMarkersControls.filter(function(markerControls){return markerControls.object3d.visible===true});var count=Object.keys(visibleMarkerControls).length;var positionDelta=new THREE.Vector3;var quaternionDelta=new THREE.Quaternion;var scaleDelta=new THREE.Vector3;var tmpMatrix=new THREE.Matrix4;for(var i=0;i<count;i++){var markerControls1=visibleMarkerControls[i];for(var j=0;j<count;j++){var markerControls2=visibleMarkerControls[j];if(i===j)continue;if(markerControls1.object3d.userData.seenCouples===undefined){markerControls1.object3d.userData.seenCouples={}}var seenCouples=markerControls1.object3d.userData.seenCouples;if(seenCouples[markerControls2.id]===undefined){seenCouples[markerControls2.id]={count:0,position:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)},quaternion:{sum:new THREE.Quaternion(0,0,0,0),average:new THREE.Quaternion(0,0,0,0)},scale:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)}}}tmpMatrix.getInverse(markerControls1.object3d.matrix);tmpMatrix.multiply(markerControls2.object3d.matrix);tmpMatrix.decompose(positionDelta,quaternionDelta,scaleDelta);var stats=seenCouples[markerControls2.id];stats.count++;THREEx.ArMultiMarkerControls.averageVector3(stats.position.sum,positionDelta,stats.count,stats.position.average);THREEx.ArMultiMarkerControls.averageQuaternion(stats.quaternion.sum,quaternionDelta,originQuaternion,stats.count,stats.quaternion.average);THREEx.ArMultiMarkerControls.averageVector3(stats.scale.sum,scaleDelta,stats.count,stats.scale.average)}}};ARjs.MarkersAreaLearning.prototype.computeResult=function(){var _this=this;var originSubControls=this.subMarkersControls[0];this.deleteResult();originSubControls.object3d.userData.result={averageMatrix:new THREE.Matrix4,confidenceFactor:1};do{var resultChanged=false;this.subMarkersControls.forEach(function(subMarkerControls){var result=subMarkerControls.object3d.userData.result;var isLearned=result!==undefined&&result.confidenceFactor>=1?true:false;if(isLearned===true)return;var otherSubControlsID=_this._getLearnedCoupleStats(subMarkerControls);if(otherSubControlsID===null){return}var otherSubControls=_this._getSubMarkerControlsByID(otherSubControlsID);var seenCoupleStats=subMarkerControls.object3d.userData.seenCouples[otherSubControlsID];var averageMatrix=new THREE.Matrix4;averageMatrix.compose(seenCoupleStats.position.average,seenCoupleStats.quaternion.average,seenCoupleStats.scale.average);var otherAverageMatrix=otherSubControls.object3d.userData.result.averageMatrix;var matrix=(new THREE.Matrix4).getInverse(otherAverageMatrix).multiply(averageMatrix);matrix=(new THREE.Matrix4).getInverse(matrix);console.assert(subMarkerControls.object3d.userData.result===undefined);subMarkerControls.object3d.userData.result={averageMatrix:matrix,confidenceFactor:1};resultChanged=true})}while(resultChanged===true)};ARjs.MarkersAreaLearning.prototype._getLearnedCoupleStats=function(subMarkerControls){if(subMarkerControls.object3d.userData.seenCouples===undefined)return null;var seenCouples=subMarkerControls.object3d.userData.seenCouples;var coupleControlsIDs=Object.keys(seenCouples).map(Number);for(var i=0;i<coupleControlsIDs.length;i++){var otherSubControlsID=coupleControlsIDs[i];var otherSubControls=this._getSubMarkerControlsByID(otherSubControlsID);var result=otherSubControls.object3d.userData.result;var isLearned=result!==undefined&&result.confidenceFactor>=1?true:false;if(isLearned===false)continue;return otherSubControlsID}return null};ARjs.MarkersAreaLearning.prototype._getSubMarkerControlsByID=function(controlsID){for(var i=0;i<this.subMarkersControls.length;i++){var subMarkerControls=this.subMarkersControls[i];if(subMarkerControls.id===controlsID){return subMarkerControls}}return null};ARjs.MarkersAreaLearning.prototype.toJSON=function(){this.computeResult();var data={meta:{createdBy:"Area Learning - AR.js "+THREEx.ArToolkitContext.REVISION,createdAt:(new Date).toJSON()},trackingBackend:this._arToolkitContext.parameters.trackingBackend,subMarkersControls:[]};var originSubControls=this.subMarkersControls[0];var originMatrixInverse=(new THREE.Matrix4).getInverse(originSubControls.object3d.matrix);this.subMarkersControls.forEach(function(subMarkerControls,index){if(subMarkerControls.object3d.userData.result===undefined)return;var poseMatrix=subMarkerControls.object3d.userData.result.averageMatrix;console.assert(poseMatrix instanceof THREE.Matrix4);var info={parameters:{},poseMatrix:poseMatrix.toArray()};if(subMarkerControls.parameters.type==="pattern"){info.parameters.type=subMarkerControls.parameters.type;info.parameters.patternUrl=subMarkerControls.parameters.patternUrl}else if(subMarkerControls.parameters.type==="barcode"){info.parameters.type=subMarkerControls.parameters.type;info.parameters.barcodeValue=subMarkerControls.parameters.barcodeValue}else console.assert(false);data.subMarkersControls.push(info)});var strJSON=JSON.stringify(data,null," ");var humanReadable=false;if(humanReadable===true){var tmp=JSON.parse(strJSON);tmp.subMarkersControls.forEach(function(markerControls){markerControls.poseMatrix=markerControls.poseMatrix.map(function(value){var roundingFactor=100;return Math.round(value*roundingFactor)/roundingFactor})});strJSON=JSON.stringify(tmp,null," ")}return strJSON};ARjs.MarkersAreaLearning.prototype.resetStats=function(){this.deleteResult();this.subMarkersControls.forEach(function(markerControls){delete markerControls.object3d.userData.seenCouples})};ARjs.MarkersAreaLearning.prototype.deleteResult=function(){this.subMarkersControls.forEach(function(markerControls){delete markerControls.object3d.userData.result})};var THREEx=THREEx||{};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkersAreaUtils=THREEx.ArMultiMarkerUtils={};ARjs.MarkersAreaUtils.navigateToLearnerPage=function(learnerBaseURL,trackingBackend){var learnerParameters={backURL:location.href,trackingBackend:trackingBackend,markersControlsParameters:ARjs.MarkersAreaUtils.createDefaultMarkersControlsParameters(trackingBackend)};location.href=learnerBaseURL+"?"+encodeURIComponent(JSON.stringify(learnerParameters))};ARjs.MarkersAreaUtils.storeDefaultMultiMarkerFile=function(trackingBackend){var file=ARjs.MarkersAreaUtils.createDefaultMultiMarkerFile(trackingBackend);localStorage.setItem("ARjsMultiMarkerFile",JSON.stringify(file))};ARjs.MarkersAreaUtils.createDefaultMultiMarkerFile=function(trackingBackend){console.assert(trackingBackend);if(trackingBackend===undefined)debugger;var link=document.createElement("a");link.href=ARjs.Context.baseURL;var absoluteBaseURL=link.href;var file={meta:{createdBy:"AR.js "+ARjs.Context.REVISION+" - Default Marker",createdAt:(new Date).toJSON()},trackingBackend:trackingBackend,subMarkersControls:[]};file.subMarkersControls[0]={parameters:{},poseMatrix:(new THREE.Matrix4).makeTranslation(0,0,0).toArray()};if(trackingBackend==="artoolkit"){file.subMarkersControls[0].parameters.type="pattern";file.subMarkersControls[0].parameters.patternUrl=absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-hiro.patt";
}else if(trackingBackend==="aruco"){file.subMarkersControls[0].parameters.type="barcode";file.subMarkersControls[0].parameters.barcodeValue=1001}else console.assert(false);return file};ARjs.MarkersAreaUtils.createDefaultMarkersControlsParameters=function(trackingBackend){var link=document.createElement("a");link.href=ARjs.Context.baseURL;var absoluteBaseURL=link.href;if(trackingBackend==="artoolkit"){var markersControlsParameters=[{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-hiro.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-kanji.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterA.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterB.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterC.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterF.patt"}]}else if(trackingBackend==="aruco"){var markersControlsParameters=[{type:"barcode",barcodeValue:1001},{type:"barcode",barcodeValue:1002},{type:"barcode",barcodeValue:1003},{type:"barcode",barcodeValue:1004},{type:"barcode",barcodeValue:1005},{type:"barcode",barcodeValue:1006}]}else console.assert(false);return markersControlsParameters};ARjs.MarkersAreaUtils.storeMarkersAreaFileFromResolution=function(trackingBackend,resolutionW,resolutionH){var areaFile=this.buildMarkersAreaFileFromResolution(trackingBackend,resolutionW,resolutionH);localStorage.setItem("ARjsMultiMarkerFile",JSON.stringify(areaFile))};ARjs.MarkersAreaUtils.buildMarkersAreaFileFromResolution=function(trackingBackend,resolutionW,resolutionH){var file={meta:{createdBy:"AR.js - Augmented Website",createdAt:(new Date).toJSON()},trackingBackend:trackingBackend,subMarkersControls:[]};var whiteMargin=.1;if(resolutionW>resolutionH){var markerImageSize=.4*resolutionH}else if(resolutionW<resolutionH){var markerImageSize=.4*resolutionW}else if(resolutionW===resolutionH){var markerImageSize=.33*resolutionW}else console.assert(false);var actualMarkerSize=markerImageSize*(1-2*whiteMargin);var deltaX=(resolutionW-markerImageSize)/2/actualMarkerSize;var deltaZ=(resolutionH-markerImageSize)/2/actualMarkerSize;var subMarkerControls=buildSubMarkerControls("center",0,0);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("topleft",-deltaX,-deltaZ);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("topright",+deltaX,-deltaZ);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("bottomleft",-deltaX,+deltaZ);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("bottomright",+deltaX,+deltaZ);file.subMarkersControls.push(subMarkerControls);return file;function buildSubMarkerControls(layout,positionX,positionZ){console.log("buildSubMarkerControls",layout,positionX,positionZ);var subMarkersControls={parameters:{},poseMatrix:(new THREE.Matrix4).makeTranslation(positionX,0,positionZ).toArray()};if(trackingBackend==="artoolkit"){layout2MarkerParametersArtoolkit(subMarkersControls.parameters,layout)}else if(trackingBackend==="aruco"){layout2MarkerParametersAruco(subMarkersControls.parameters,layout)}else console.assert(false);return subMarkersControls}function layout2MarkerParametersArtoolkit(parameters,layout){var link=document.createElement("a");link.href=ARjs.Context.baseURL;var absoluteBaseURL=link.href;var layout2PatternUrl={center:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-hiro.patt"),topleft:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterA.patt"),topright:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterB.patt"),bottomleft:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterC.patt"),bottomright:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterF.patt")};console.assert(layout2PatternUrl[layout]!==undefined);parameters.type="pattern";parameters.patternUrl=layout2PatternUrl[layout];return;function convertRelativeUrlToAbsolute(relativeUrl){var tmpLink=document.createElement("a");tmpLink.href=relativeUrl;return tmpLink.href}}function layout2MarkerParametersAruco(parameters,layout){var layout2Barcode={center:1001,topleft:1002,topright:1003,bottomleft:1004,bottomright:1005};console.assert(layout2Barcode[layout]);parameters.type="barcode";parameters.barcodeValue=layout2Barcode[layout]}};
three.js/contribs/portableAR.js/build/portable-ar.js
浏览文件 @
639d6889
...
...
@@ -49364,7 +49364,7 @@ Object.assign( ARjs.Context.prototype, THREE.EventDispatcher.prototype );
// ARjs.Context.baseURL = '../'
// default to github page
ARjs.Context.baseURL = 'https://jeromeetienne.github.io/AR.js/three.js/'
ARjs.Context.REVISION = '1.6.
1
'
ARjs.Context.REVISION = '1.6.
2
'
three.js/contribs/portableAR.js/build/portable-ar.min.js
浏览文件 @
639d6889
...
...
@@ -47,6 +47,6 @@ n=0;o=m;while(1){if((c[o>>2]|0)==(p|0))c[o>>2]=j;n=n+1|0;if((n|0)>=(r|0))break;e
a[I+v>>0]=F>>>31;F=(F|0)>-1?F:0-F|0;v=v+-1|0;y=(F|0)<(y|0)?F:y}if((z|0)>0)z=z+-1|0;else break}if((D|0)>0)D=D+-1|0;else break}break}case 3:{v=119;y=255;D=13;while(1){C=D+-3|0;B=D&-2;A=(B|0)==12;B=(B|0)==0;z=0;do{if(((z+-3|C)>>>0>=8?!(A&z>>>0<2|(z|D)>>>0<2):0)?!(B&(z&-2|0)==12):0){F=(d[K+((z*14|0)+D)>>0]|0)-H|0;a[I+v>>0]=F>>>31;F=(F|0)>-1?F:0-F|0;v=v+-1|0;y=(F|0)<(y|0)?F:y}z=z+1|0}while((z|0)!=14);if((D|0)>0)D=D+-1|0;else break}break}default:y=255}c[t>>2]=G;h[u>>3]=(y|0)>30?1.0:+(y|0)/30.0;y=Ie(2830,0,0,I,J)|0;if((y|0)<0){y=-4;v=0;z=0}else{if(w)c[w>>2]=y;z=J;y=0;v=c[z>>2]|0;z=c[z+4>>2]|0}}else{c[t>>2]=0;h[u>>3]=-1.0;y=-2;v=0;z=0}while(0);if((y|0)<0){c[s>>2]=-1;break}if((v|0)==-1&(z|0)==-1){c[s>>2]=-1;y=-5;break}c[s>>2]=(v&-32768|0)==0&0==0?v&32767:0;if(!x)y=0;else{y=x;c[y>>2]=v;c[y+4>>2]=z;y=0}}else y=1;while(0);b:do switch(f|0){case 0:case 1:case 3:case 4:{if(!b){c[p>>2]=-1;v=-1;break b}v=b+28|0;z=c[v>>2]|0;A=z<<2;switch(f|0){case 0:case 3:if((Ee(e,0,z,A,g,j,k,l,m,n,o,K)|0)<0){c[p>>2]=-1;v=-6;break b}else{v=Ge(b,0,K,c[v>>2]|0,p,q,r)|0;break b}default:if((Ee(e,1,z,A,g,j,k,l,m,n,o,K)|0)<0){c[p>>2]=-1;v=-6;break b}else{v=Ge(b,1,K,c[v>>2]|0,p,q,r)|0;break b}}}default:v=1}while(0);if((y|0)!=1){if((v|0)!=1)y=(v&y|0)<0?v:0}else y=v;i=L;return y|0}function _j(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,j=0,k=0;k=i;i=i+16|0;b=k+8|0;h=k+4|0;d=k;c[h>>2]=a;do if(a>>>0>=212){g=(a>>>0)/210|0;e=g*210|0;c[d>>2]=a-e;b=($j(3712,3904,d,b)|0)-3712>>2;f=b;b=(c[3712+(b<<2)>>2]|0)+e|0;a:while(1){e=5;while(1){if(e>>>0>=47){e=211;j=8;break}d=c[3520+(e<<2)>>2]|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=106;break a}if((b|0)==($(a,d)|0))break;else e=e+1|0}b:do if((j|0)==8)while(1){j=0;d=(b>>>0)/(e>>>0)|0;if(d>>>0<e>>>0){j=105;break a}if((b|0)==($(d,e)|0))break b;d=e+10|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+12|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+16|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+18|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+22|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+28|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+30|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+36|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+40|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+42|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+46|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+52|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+58|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+60|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+66|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+70|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+72|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+78|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+82|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+88|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+96|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+100|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+102|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+106|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+108|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+112|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+120|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+126|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+130|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+136|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+138|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+142|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+148|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+150|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+156|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+162|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+166|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+168|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+172|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+178|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+180|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+186|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+190|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+192|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+196|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+198|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break b;d=e+208|0;a=(b>>>0)/(d>>>0)|0;if(a>>>0<d>>>0){j=105;break a}if((b|0)==($(a,d)|0))break;else{e=e+210|0;j=8}}while(0);e=f+1|0;b=(e|0)==48;e=b?0:e;b=(b&1)+g|0;f=e;g=b;b=(c[3712+(e<<2)>>2]|0)+(b*210|0)|0}if((j|0)==105){c[h>>2]=b;break}else if((j|0)==106){c[h>>2]=b;break}}else b=c[($j(3520,3712,h,b)|0)>>2]|0;while(0);i=k;return b|0}function $j(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0;f=c[d>>2]|0;e=a;d=b-a>>2;a:while(1){while(1){if(!d)break a;a=(d|0)/2|0;if((c[e+(a<<2)>>2]|0)>>>0<f>>>0)break;else d=a}e=e+(a+1<<2)|0;d=d+-1-a|0}return e|0}function ak(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0;if(e>>>0>4294967279)oi(b);if(e>>>0<11){a[b>>0]=e<<1;b=b+1|0}else{g=e+16&-16;f=Kh(g)|0;c[b+8>>2]=f;c[b>>2]=g|1;c[b+4>>2]=e;b=f}ik(b|0,d|0,e|0)|0;a[b+e>>0]=0;return}function bk(b){b=b|0;if(a[b>>0]&1)Lh(c[b+8>>2]|0);return}function ck(){}function dk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;d=b-d-(c>>>0>a>>>0|0)>>>0;return(D=d,a-c>>>0|0)|0}function ek(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0;f=b+e|0;if((e|0)>=20){d=d&255;h=b&3;i=d|d<<8|d<<16|d<<24;g=f&~3;if(h){h=b+4-h|0;while((b|0)<(h|0)){a[b>>0]=d;b=b+1|0}}while((b|0)<(g|0)){c[b>>2]=i;b=b+4|0}}while((b|0)<(f|0)){a[b>>0]=d;b=b+1|0}return b-e|0}function fk(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){D=b<<c|(a&(1<<c)-1<<32-c)>>>32-c;return a<<c}D=a<<c-32;return 0}function gk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;c=a+c>>>0;return(D=b+d+(c>>>0<a>>>0|0)>>>0,c|0)|0}function hk(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){D=b>>>c;return a>>>c|(b&(1<<c)-1)<<32-c}D=0;return b>>>c-32|0}function ik(b,d,e){b=b|0;d=d|0;e=e|0;var f=0;if((e|0)>=4096)return Xa(b|0,d|0,e|0)|0;f=b|0;if((b&3)==(d&3)){while(b&3){if(!e)return f|0;a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}while((e|0)>=4){c[b>>2]=c[d>>2];b=b+4|0;d=d+4|0;e=e-4|0}}while((e|0)>0){a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}return f|0}function jk(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){D=b>>c;return a>>>c|(b&(1<<c)-1)<<32-c}D=(b|0)<0?-1:0;return b>>c-32|0}function kk(b){b=b|0;var c=0;c=a[m+(b&255)>>0]|0;if((c|0)<8)return c|0;c=a[m+(b>>8&255)>>0]|0;if((c|0)<8)return c+8|0;c=a[m+(b>>16&255)>>0]|0;if((c|0)<8)return c+16|0;return(a[m+(b>>>24)>>0]|0)+24|0}function lk(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0;f=a&65535;e=b&65535;c=$(e,f)|0;d=a>>>16;a=(c>>>16)+($(e,d)|0)|0;e=b>>>16;b=$(e,f)|0;return(D=(a>>>16)+($(e,d)|0)+(((a&65535)+b|0)>>>16)|0,a+b<<16|c&65535|0)|0}function mk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0;j=b>>31|((b|0)<0?-1:0)<<1;i=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;f=d>>31|((d|0)<0?-1:0)<<1;e=((d|0)<0?-1:0)>>31|((d|0)<0?-1:0)<<1;h=dk(j^a,i^b,j,i)|0;g=D;a=f^j;b=e^i;return dk((rk(h,g,dk(f^c,e^d,f,e)|0,D,0)|0)^a,D^b,a,b)|0}function nk(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0;f=i;i=i+16|0;j=f|0;h=b>>31|((b|0)<0?-1:0)<<1;g=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;l=e>>31|((e|0)<0?-1:0)<<1;k=((e|0)<0?-1:0)>>31|((e|0)<0?-1:0)<<1;a=dk(h^a,g^b,h,g)|0;b=D;rk(a,b,dk(l^d,k^e,l,k)|0,D,j)|0;e=dk(c[j>>2]^h,c[j+4>>2]^g,h,g)|0;d=D;i=f;return(D=d,e)|0}function ok(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0;e=a;f=c;c=lk(e,f)|0;a=D;return(D=($(b,f)|0)+($(d,e)|0)+a|a&0,c|0|0)|0}function pk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;return rk(a,b,c,d,0)|0}function qk(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0;g=i;i=i+16|0;f=g|0;rk(a,b,d,e,f)|0;i=g;return(D=c[f+4>>2]|0,c[f>>2]|0)|0}function rk(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;l=a;j=b;k=j;h=d;n=e;i=n;if(!k){g=(f|0)!=0;if(!i){if(g){c[f>>2]=(l>>>0)%(h>>>0);c[f+4>>2]=0}n=0;f=(l>>>0)/(h>>>0)>>>0;return(D=n,f)|0}else{if(!g){n=0;f=0;return(D=n,f)|0}c[f>>2]=a|0;c[f+4>>2]=b&0;n=0;f=0;return(D=n,f)|0}}g=(i|0)==0;do if(h){if(!g){g=(ba(i|0)|0)-(ba(k|0)|0)|0;if(g>>>0<=31){m=g+1|0;i=31-g|0;b=g-31>>31;h=m;a=l>>>(m>>>0)&b|k<<i;b=k>>>(m>>>0)&b;g=0;i=l<<i;break}if(!f){n=0;f=0;return(D=n,f)|0}c[f>>2]=a|0;c[f+4>>2]=j|b&0;n=0;f=0;return(D=n,f)|0}g=h-1|0;if(g&h){i=(ba(h|0)|0)+33-(ba(k|0)|0)|0;p=64-i|0;m=32-i|0;j=m>>31;o=i-32|0;b=o>>31;h=i;a=m-1>>31&k>>>(o>>>0)|(k<<m|l>>>(i>>>0))&b;b=b&k>>>(i>>>0);g=l<<p&j;i=(k<<p|l>>>(o>>>0))&j|l<<m&i-33>>31;break}if(f){c[f>>2]=g&l;c[f+4>>2]=0}if((h|0)==1){o=j|b&0;p=a|0|0;return(D=o,p)|0}else{p=kk(h|0)|0;o=k>>>(p>>>0)|0;p=k<<32-p|l>>>(p>>>0)|0;return(D=o,p)|0}}else{if(g){if(f){c[f>>2]=(k>>>0)%(h>>>0);c[f+4>>2]=0}o=0;p=(k>>>0)/(h>>>0)>>>0;return(D=o,p)|0}if(!l){if(f){c[f>>2]=0;c[f+4>>2]=(k>>>0)%(i>>>0)}o=0;p=(k>>>0)/(i>>>0)>>>0;return(D=o,p)|0}g=i-1|0;if(!(g&i)){if(f){c[f>>2]=a|0;c[f+4>>2]=g&k|b&0}o=0;p=k>>>((kk(i|0)|0)>>>0);return(D=o,p)|0}g=(ba(i|0)|0)-(ba(k|0)|0)|0;if(g>>>0<=30){b=g+1|0;i=31-g|0;h=b;a=k<<i|l>>>(b>>>0);b=k>>>(b>>>0);g=0;i=l<<i;break}if(!f){o=0;p=0;return(D=o,p)|0}c[f>>2]=a|0;c[f+4>>2]=j|b&0;o=0;p=0;return(D=o,p)|0}while(0);if(!h){k=i;j=0;i=0}else{m=d|0|0;l=n|e&0;k=gk(m|0,l|0,-1,-1)|0;d=D;j=i;i=0;do{e=j;j=g>>>31|j<<1;g=i|g<<1;e=a<<1|e>>>31|0;n=a>>>31|b<<1|0;dk(k,d,e,n)|0;p=D;o=p>>31|((p|0)<0?-1:0)<<1;i=o&1;a=dk(e,n,o&m,(((p|0)<0?-1:0)>>31|((p|0)<0?-1:0)<<1)&l)|0;b=D;h=h-1|0}while((h|0)!=0);k=j;j=0}h=0;if(f){c[f>>2]=a;c[f+4>>2]=b}o=(g|0)>>>31|(k|h)<<1|(h<<1|g>>>31)&0|j;p=(g<<1|0>>>31)&-2|i;return(D=o,p)|0}function sk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;return Qb[a&15](b|0,c|0,d|0)|0}function tk(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;Rb[a&3](b|0,c|0,d|0,e|0,f|0)}function uk(a,b,c){a=a|0;b=b|0;c=c|0;return+Sb[a&1](b|0,c|0)}function vk(a,b,c){a=a|0;b=b|0;c=+c;Tb[a&3](b|0,+c)}function wk(a,b){a=a|0;b=b|0;return+Ub[a&3](b|0)}function xk(a){a=a|0;return Vb[a&1]()|0}function yk(a,b){a=a|0;b=b|0;Wb[a&15](b|0)}function zk(a,b,c){a=a|0;b=b|0;c=c|0;Xb[a&7](b|0,c|0)}function Ak(a,b){a=a|0;b=b|0;return Yb[a&31](b|0)|0}function Bk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;Zb[a&1](b|0,c|0,d|0)}function Ck(a){a=a|0;_b[a&0]()}function Dk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=+d;$b[a&3](b|0,c|0,+d)}function Ek(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;return ac[a&1](b|0,c|0,d|0,e|0)|0}function Fk(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;bc[a&3](b|0,c|0,d|0,e|0,f|0,g|0)}function Gk(a,b,c){a=a|0;b=b|0;c=c|0;return cc[a&15](b|0,c|0)|0}function Hk(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;dc[a&3](b|0,c|0,d|0,e|0)}function Ik(a,b,c){a=a|0;b=b|0;c=c|0;ca(0);return 0}function Jk(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;ca(1)}function Kk(a,b){a=a|0;b=b|0;ca(2);return 0.0}function Lk(a,b){a=a|0;b=+b;ca(3)}function Mk(a){a=a|0;ca(4);return 0.0}function Nk(){ca(5);return 0}function Ok(a){a=a|0;ca(6)}function Pk(a,b){a=a|0;b=b|0;ca(7)}function Qk(a){a=a|0;ca(8);return 0}function Rk(a,b,c){a=a|0;b=b|0;c=c|0;ca(9)}function Sk(){ca(10)}function Tk(a,b,c){a=a|0;b=b|0;c=+c;ca(11)}function Uk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;ca(12);return 0}function Vk(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;ca(13)}function Wk(a,b){a=a|0;b=b|0;ca(14);return 0}function Xk(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;ca(15)}var Qb=[Ik,Zh,_h,Qj,Qi,Pi,Ri,Ag,sg,qg,rg,yg,kh,jh,Oi,Mj];var Rb=[Jk,ki,ji,gi];var Sb=[Kk,dh];var Tb=[Lk,Wf,Yf,ag];var Ub=[Mk,Xf,Zf,bg];var Vb=[Nk,Nf];var Wb=[Ok,Mh,Nh,Sh,Vh,Th,Uh,Wh,Xh,Yh,Mf,Xg,Yg,Ij,Jj,Ok];var Xb=[Pk,ig,gg,_f,cg,eg,ng,gh];var Yb=[Qk,Oh,Ni,Pf,Vf,Qf,wg,xg,mg,lg,jg,hg,$f,dg,fg,og,fh,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk,Qk];var Zb=[Rk,ch];var _b=[Sk];var $b=[Tk,eh,bh,Tk];var ac=[Uk,mh];var bc=[Vk,ni,mi,li];var cc=[Wk,Df,Sf,Tf,Uf,tg,vg,ug,zg,kg,lh,hh,Wk,Wk,Wk,Wk];var dc=[Xk,ai,bi,di];return{_i64Subtract:dk,_fflush:Yi,_i64Add:gk,_memset:ek,_malloc:Uj,_memcpy:ik,___getTypeName:Ah,_bitshift64Lshr:hk,_free:Vj,___errno_location:qi,_bitshift64Shl:fk,__GLOBAL__sub_I_ARToolKitJS_cpp:Wg,__GLOBAL__sub_I_bind_cpp:Ch,runPostSets:ck,stackAlloc:ec,stackSave:fc,stackRestore:gc,establishStackSpace:hc,setThrew:ic,setTempRet0:lc,getTempRet0:mc,dynCall_iiii:sk,dynCall_viiiii:tk,dynCall_dii:uk,dynCall_vid:vk,dynCall_di:wk,dynCall_i:xk,dynCall_vi:yk,dynCall_vii:zk,dynCall_ii:Ak,dynCall_viii:Bk,dynCall_v:Ck,dynCall_viid:Dk,dynCall_iiiii:Ek,dynCall_viiiiii:Fk,dynCall_iii:Gk,dynCall_viiii:Hk}}(Module.asmGlobalArg,Module.asmLibraryArg,buffer);var _i64Subtract=Module["_i64Subtract"]=asm["_i64Subtract"];var __GLOBAL__sub_I_bind_cpp=Module["__GLOBAL__sub_I_bind_cpp"]=asm["__GLOBAL__sub_I_bind_cpp"];var _fflush=Module["_fflush"]=asm["_fflush"];var __GLOBAL__sub_I_ARToolKitJS_cpp=Module["__GLOBAL__sub_I_ARToolKitJS_cpp"]=asm["__GLOBAL__sub_I_ARToolKitJS_cpp"];var _i64Add=Module["_i64Add"]=asm["_i64Add"];var _memset=Module["_memset"]=asm["_memset"];var runPostSets=Module["runPostSets"]=asm["runPostSets"];var _malloc=Module["_malloc"]=asm["_malloc"];var _memcpy=Module["_memcpy"]=asm["_memcpy"];var ___getTypeName=Module["___getTypeName"]=asm["___getTypeName"];var _bitshift64Lshr=Module["_bitshift64Lshr"]=asm["_bitshift64Lshr"];var _free=Module["_free"]=asm["_free"];var ___errno_location=Module["___errno_location"]=asm["___errno_location"];var _bitshift64Shl=Module["_bitshift64Shl"]=asm["_bitshift64Shl"];var dynCall_iiii=Module["dynCall_iiii"]=asm["dynCall_iiii"];var dynCall_viiiii=Module["dynCall_viiiii"]=asm["dynCall_viiiii"];var dynCall_dii=Module["dynCall_dii"]=asm["dynCall_dii"];var dynCall_vid=Module["dynCall_vid"]=asm["dynCall_vid"];var dynCall_di=Module["dynCall_di"]=asm["dynCall_di"];var dynCall_i=Module["dynCall_i"]=asm["dynCall_i"];var dynCall_vi=Module["dynCall_vi"]=asm["dynCall_vi"];var dynCall_vii=Module["dynCall_vii"]=asm["dynCall_vii"];var dynCall_ii=Module["dynCall_ii"]=asm["dynCall_ii"];var dynCall_viii=Module["dynCall_viii"]=asm["dynCall_viii"];var dynCall_v=Module["dynCall_v"]=asm["dynCall_v"];var dynCall_viid=Module["dynCall_viid"]=asm["dynCall_viid"];var dynCall_iiiii=Module["dynCall_iiiii"]=asm["dynCall_iiiii"];var dynCall_viiiiii=Module["dynCall_viiiiii"]=asm["dynCall_viiiiii"];var dynCall_iii=Module["dynCall_iii"]=asm["dynCall_iii"];var dynCall_viiii=Module["dynCall_viiii"]=asm["dynCall_viiii"];Runtime.stackAlloc=asm["stackAlloc"];Runtime.stackSave=asm["stackSave"];Runtime.stackRestore=asm["stackRestore"];Runtime.establishStackSpace=asm["establishStackSpace"];Runtime.setTempRet0=asm["setTempRet0"];Runtime.getTempRet0=asm["getTempRet0"];function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}ExitStatus.prototype=new Error;ExitStatus.prototype.constructor=ExitStatus;var initialStackTop;var preloadStartTime=null;var calledMain=false;dependenciesFulfilled=function runCaller(){if(!Module["calledRun"])run();if(!Module["calledRun"])dependenciesFulfilled=runCaller};Module["callMain"]=Module.callMain=function callMain(args){assert(runDependencies==0,"cannot call main when async dependencies remain! (listen on __ATMAIN__)");assert(__ATPRERUN__.length==0,"cannot call main when preRun functions remain to be called");args=args||[];ensureInitRuntime();var argc=args.length+1;function pad(){for(var i=0;i<4-1;i++){argv.push(0)}}var argv=[allocate(intArrayFromString(Module["thisProgram"]),"i8",ALLOC_NORMAL)];pad();for(var i=0;i<argc-1;i=i+1){argv.push(allocate(intArrayFromString(args[i]),"i8",ALLOC_NORMAL));pad()}argv.push(0);argv=allocate(argv,"i32",ALLOC_NORMAL);try{var ret=Module["_main"](argc,argv,0);exit(ret,true)}catch(e){if(e instanceof ExitStatus){return}else if(e=="SimulateInfiniteLoop"){Module["noExitRuntime"]=true;return}else{if(e&&typeof e==="object"&&e.stack)Module.printErr("exception thrown: "+[e,e.stack]);throw e}}finally{calledMain=true}};function run(args){args=args||Module["arguments"];if(preloadStartTime===null)preloadStartTime=Date.now();if(runDependencies>0){return}preRun();if(runDependencies>0)return;if(Module["calledRun"])return;function doRun(){if(Module["calledRun"])return;Module["calledRun"]=true;if(ABORT)return;ensureInitRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(Module["_main"]&&shouldRunNow)Module["callMain"](args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=Module.run=run;function exit(status,implicit){if(implicit&&Module["noExitRuntime"]){return}if(Module["noExitRuntime"]){}else{ABORT=true;EXITSTATUS=status;STACKTOP=initialStackTop;exitRuntime();if(Module["onExit"])Module["onExit"](status)}if(ENVIRONMENT_IS_NODE){process["stdout"]["once"]("drain",function(){process["exit"](status)});console.log(" ");setTimeout(function(){process["exit"](status)},500)}else if(ENVIRONMENT_IS_SHELL&&typeof quit==="function"){quit(status)}throw new ExitStatus(status)}Module["exit"]=Module.exit=exit;var abortDecorators=[];function abort(what){if(what!==undefined){Module.print(what);Module.printErr(what);what=JSON.stringify(what)}else{what=""}ABORT=true;EXITSTATUS=1;var extra="\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.";var output="abort("+what+") at "+stackTrace()+extra;if(abortDecorators){abortDecorators.forEach(function(decorator){output=decorator(output,what)})}throw output}Module["abort"]=Module.abort=abort;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=true;if(Module["noInitialRun"]){shouldRunNow=false}run();(function(){"use strict";var ARController=function(width,height,camera){var id;var w=width,h=height;this.orientation="landscape";this.listeners={};if(typeof width!=="number"){var image=width;camera=height;w=image.videoWidth||image.width;h=image.videoHeight||image.height;this.image=image}this.defaultMarkerWidth=1;this.patternMarkers={};this.barcodeMarkers={};this.transform_mat=new Float32Array(16);this.canvas=document.createElement("canvas");this.canvas.width=w;this.canvas.height=h;this.ctx=this.canvas.getContext("2d");this.videoWidth=w;this.videoHeight=h;if(typeof camera==="string"){var self=this;this.cameraParam=new ARCameraParam(camera,function(){self._initialize()},function(err){console.error("ARController: Failed to load ARCameraParam",err)})}else{this.cameraParam=camera;this._initialize()}};ARController.prototype.dispose=function(){artoolkit.teardown(this.id);for(var t in this){this[t]=null}};ARController.prototype.process=function(image){this.detectMarker(image);var markerNum=this.getMarkerNum();var k,o;for(k in this.patternMarkers){o=this.patternMarkers[k];o.inPrevious=o.inCurrent;o.inCurrent=false}for(k in this.barcodeMarkers){o=this.barcodeMarkers[k];o.inPrevious=o.inCurrent;o.inCurrent=false}for(var i=0;i<markerNum;i++){var markerInfo=this.getMarker(i);var markerType=artoolkit.UNKNOWN_MARKER;var visible=this.trackPatternMarkerId(-1);if(markerInfo.idPatt>-1&&(markerInfo.id===markerInfo.idPatt||markerInfo.idMatrix===-1)){visible=this.trackPatternMarkerId(markerInfo.idPatt);markerType=artoolkit.PATTERN_MARKER;if(markerInfo.dir!==markerInfo.dirPatt){this.setMarkerInfoDir(i,markerInfo.dirPatt)}}else if(markerInfo.idMatrix>-1){visible=this.trackBarcodeMarkerId(markerInfo.idMatrix);markerType=artoolkit.BARCODE_MARKER;if(markerInfo.dir!==markerInfo.dirMatrix){this.setMarkerInfoDir(i,markerInfo.dirMatrix)}}if(markerType!==artoolkit.UNKNOWN_MARKER&&visible.inPrevious){this.getTransMatSquareCont(i,visible.markerWidth,visible.matrix,visible.matrix)}else{this.getTransMatSquare(i,visible.markerWidth,visible.matrix)}visible.inCurrent=true;this.transMatToGLMat(visible.matrix,this.transform_mat);this.dispatchEvent({name:"getMarker",target:this,data:{index:i,type:markerType,marker:markerInfo,matrix:this.transform_mat}})}var multiMarkerCount=this.getMultiMarkerCount();for(var i=0;i<multiMarkerCount;i++){var subMarkerCount=this.getMultiMarkerPatternCount(i);var visible=false;artoolkit.getTransMatMultiSquareRobust(this.id,i);this.transMatToGLMat(this.marker_transform_mat,this.transform_mat);for(var j=0;j<subMarkerCount;j++){var multiEachMarkerInfo=this.getMultiEachMarker(i,j);if(multiEachMarkerInfo.visible>=0){visible=true;this.dispatchEvent({name:"getMultiMarker",target:this,data:{multiMarkerId:i,matrix:this.transform_mat}});break}}if(visible){for(var j=0;j<subMarkerCount;j++){var multiEachMarkerInfo=this.getMultiEachMarker(i,j);this.transMatToGLMat(this.marker_transform_mat,this.transform_mat);this.dispatchEvent({name:"getMultiMarkerSub",target:this,data:{multiMarkerId:i,markerIndex:j,marker:multiEachMarkerInfo,matrix:this.transform_mat}})}}}if(this._bwpointer){this.debugDraw()}};ARController.prototype.trackPatternMarkerId=function(id,markerWidth){var obj=this.patternMarkers[id];if(!obj){this.patternMarkers[id]=obj={inPrevious:false,inCurrent:false,matrix:new Float32Array(12),markerWidth:markerWidth||this.defaultMarkerWidth}}if(markerWidth){obj.markerWidth=markerWidth}return obj};ARController.prototype.trackBarcodeMarkerId=function(id,markerWidth){var obj=this.barcodeMarkers[id];if(!obj){this.barcodeMarkers[id]=obj={inPrevious:false,inCurrent:false,matrix:new Float32Array(12),markerWidth:markerWidth||this.defaultMarkerWidth}}if(markerWidth){obj.markerWidth=markerWidth}return obj};ARController.prototype.getMultiMarkerCount=function(){return artoolkit.getMultiMarkerCount(this.id)};ARController.prototype.getMultiMarkerPatternCount=function(multiMarkerId){return artoolkit.getMultiMarkerNum(this.id,multiMarkerId)};ARController.prototype.addEventListener=function(name,callback){if(!this.listeners[name]){this.listeners[name]=[]}this.listeners[name].push(callback)};ARController.prototype.removeEventListener=function(name,callback){if(this.listeners[name]){var index=this.listeners[name].indexOf(callback);if(index>-1){this.listeners[name].splice(index,1)}}};ARController.prototype.dispatchEvent=function(event){var listeners=this.listeners[event.name];if(listeners){for(var i=0;i<listeners.length;i++){listeners[i].call(this,event)}}};ARController.prototype.debugSetup=function(){document.body.appendChild(this.canvas);this.setDebugMode(1);this._bwpointer=this.getProcessingImage()};ARController.prototype.loadMarker=function(markerURL,onSuccess,onError){return artoolkit.addMarker(this.id,markerURL,onSuccess,onError)};ARController.prototype.loadMultiMarker=function(markerURL,onSuccess,onError){return artoolkit.addMultiMarker(this.id,markerURL,onSuccess,onError)};ARController.prototype.getTransMatSquare=function(markerIndex,markerWidth,dst){artoolkit.getTransMatSquare(this.id,markerIndex,markerWidth);dst.set(this.marker_transform_mat);return dst};ARController.prototype.getTransMatSquareCont=function(markerIndex,markerWidth,previousMarkerTransform,dst){this.marker_transform_mat.set(previousMarkerTransform);artoolkit.getTransMatSquareCont(this.id,markerIndex,markerWidth);dst.set(this.marker_transform_mat);return dst};ARController.prototype.getTransMatMultiSquare=function(multiMarkerId,dst){artoolkit.getTransMatMultiSquare(this.id,multiMarkerId);dst.set(this.marker_transform_mat);return dst};ARController.prototype.getTransMatMultiSquareRobust=function(multiMarkerId,dst){artoolkit.getTransMatMultiSquare(this.id,multiMarkerId);dst.set(this.marker_transform_mat);return dst};ARController.prototype.transMatToGLMat=function(transMat,glMat,scale){glMat[0+0*4]=transMat[0];glMat[0+1*4]=transMat[1];glMat[0+2*4]=transMat[2];glMat[0+3*4]=transMat[3];glMat[1+0*4]=transMat[4];glMat[1+1*4]=transMat[5];glMat[1+2*4]=transMat[6];glMat[1+3*4]=transMat[7];glMat[2+0*4]=transMat[8];glMat[2+1*4]=transMat[9];glMat[2+2*4]=transMat[10];glMat[2+3*4]=transMat[11];glMat[3+0*4]=0;glMat[3+1*4]=0;glMat[3+2*4]=0;glMat[3+3*4]=1;if(scale!=undefined&&scale!==0){glMat[12]*=scale;glMat[13]*=scale;glMat[14]*=scale}return glMat};ARController.prototype.detectMarker=function(image){if(this._copyImageToHeap(image)){return artoolkit.detectMarker(this.id)}return-99};ARController.prototype.getMarkerNum=function(){return artoolkit.getMarkerNum(this.id)};ARController.prototype.getMarker=function(markerIndex){if(0===artoolkit.getMarker(this.id,markerIndex)){return artoolkit.markerInfo}};ARController.prototype.setMarkerInfoVertex=function(markerIndex,vertexData){for(var i=0;i<vertexData.length;i++){this.marker_transform_mat[i*2+0]=vertexData[i][0];this.marker_transform_mat[i*2+1]=vertexData[i][1]}return artoolkit.setMarkerInfoVertex(this.id,markerIndex)};ARController.prototype.cloneMarkerInfo=function(markerInfo){return JSON.parse(JSON.stringify(markerInfo))};ARController.prototype.getMultiEachMarker=function(multiMarkerId,markerIndex){if(0===artoolkit.getMultiEachMarker(this.id,multiMarkerId,markerIndex)){return artoolkit.multiEachMarkerInfo}};ARController.prototype.getTransformationMatrix=function(){return this.transform_mat};ARController.prototype.getCameraMatrix=function(){return this.camera_mat};ARController.prototype.getMarkerTransformationMatrix=function(){return this.marker_transform_mat};ARController.prototype.setDebugMode=function(mode){return artoolkit.setDebugMode(this.id,mode)};ARController.prototype.getDebugMode=function(){return artoolkit.getDebugMode(this.id)};ARController.prototype.getProcessingImage=function(){return artoolkit.getProcessingImage(this.id)};ARController.prototype.setLogLevel=function(mode){return artoolkit.setLogLevel(mode)};ARController.prototype.getLogLevel=function(){return artoolkit.getLogLevel()};ARController.prototype.setMarkerInfoDir=function(markerIndex,dir){return artoolkit.setMarkerInfoDir(this.id,markerIndex,dir)};ARController.prototype.setProjectionNearPlane=function(value){return artoolkit.setProjectionNearPlane(this.id,value)};ARController.prototype.getProjectionNearPlane=function(){return artoolkit.getProjectionNearPlane(this.id)};ARController.prototype.setProjectionFarPlane=function(value){return artoolkit.setProjectionFarPlane(this.id,value)};ARController.prototype.getProjectionFarPlane=function(){return artoolkit.getProjectionFarPlane(this.id)};ARController.prototype.setThresholdMode=function(mode){return artoolkit.setThresholdMode(this.id,mode)};ARController.prototype.getThresholdMode=function(){return artoolkit.getThresholdMode(this.id)};ARController.prototype.setThreshold=function(threshold){return artoolkit.setThreshold(this.id,threshold)};ARController.prototype.getThreshold=function(){return artoolkit.getThreshold(this.id)};ARController.prototype.setPatternDetectionMode=function(value){return artoolkit.setPatternDetectionMode(this.id,value)};ARController.prototype.getPatternDetectionMode=function(){return artoolkit.getPatternDetectionMode(this.id)};ARController.prototype.setMatrixCodeType=function(value){return artoolkit.setMatrixCodeType(this.id,value)};ARController.prototype.getMatrixCodeType=function(){return artoolkit.getMatrixCodeType(this.id)};ARController.prototype.setLabelingMode=function(value){return artoolkit.setLabelingMode(this.id,value)};ARController.prototype.getLabelingMode=function(){return artoolkit.getLabelingMode(this.id)};ARController.prototype.setPattRatio=function(value){return artoolkit.setPattRatio(this.id,value)};ARController.prototype.getPattRatio=function(){return artoolkit.getPattRatio(this.id)};ARController.prototype.setImageProcMode=function(value){return artoolkit.setImageProcMode(this.id,value)};ARController.prototype.getImageProcMode=function(){return artoolkit.getImageProcMode(this.id)};ARController.prototype.debugDraw=function(){var debugBuffer=new Uint8ClampedArray(Module.HEAPU8.buffer,this._bwpointer,this.framesize);var id=new ImageData(debugBuffer,this.canvas.width,this.canvas.height);this.ctx.putImageData(id,0,0);var marker_num=this.getMarkerNum();for(var i=0;i<marker_num;i++){this._debugMarker(this.getMarker(i))}};ARController.prototype._initialize=function(){this.id=artoolkit.setup(this.canvas.width,this.canvas.height,this.cameraParam.id);var params=artoolkit.frameMalloc;this.framepointer=params.framepointer;this.framesize=params.framesize;this.dataHeap=new Uint8Array(Module.HEAPU8.buffer,this.framepointer,this.framesize);this.camera_mat=new Float64Array(Module.HEAPU8.buffer,params.camera,16);this.marker_transform_mat=new Float64Array(Module.HEAPU8.buffer,params.transform,12);this.setProjectionNearPlane(.1);this.setProjectionFarPlane(1e3);var self=this;setTimeout(function(){if(self.onload){self.onload()}self.dispatchEvent({name:"load",target:self})},1)};ARController.prototype._copyImageToHeap=function(image){if(!image){image=this.image}if(image.nodeName==="IMG"&&image.width>image.height||image.nodeName==="VIDEO"&&image.videoWidth>image.videoHeight){this.ctx.drawImage(image,0,0,this.canvas.width,this.canvas.height)}else{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);var scale=this.canvas.height/this.canvas.width;var scaledHeight=this.canvas.width*scale;var scaledWidth=this.canvas.height*scale;var marginLeft=(this.canvas.width-scaledWidth)/2;this.ctx.drawImage(image,marginLeft,0,scaledWidth,scaledHeight)}var imageData=this.ctx.getImageData(0,0,this.canvas.width,this.canvas.height);var data=imageData.data;if(this.dataHeap){this.dataHeap.set(data);return true}return false};ARController.prototype._debugMarker=function(marker){var vertex,pos;vertex=marker.vertex;var ctx=this.ctx;ctx.strokeStyle="red";ctx.beginPath();ctx.moveTo(vertex[0][0],vertex[0][1]);ctx.lineTo(vertex[1][0],vertex[1][1]);ctx.stroke();ctx.beginPath();ctx.moveTo(vertex[2][0],vertex[2][1]);ctx.lineTo(vertex[3][0],vertex[3][1]);ctx.stroke();ctx.strokeStyle="green";ctx.beginPath();ctx.lineTo(vertex[1][0],vertex[1][1]);ctx.lineTo(vertex[2][0],vertex[2][1]);ctx.stroke();ctx.beginPath();ctx.moveTo(vertex[3][0],vertex[3][1]);ctx.lineTo(vertex[0][0],vertex[0][1]);ctx.stroke();pos=marker.pos;ctx.beginPath();ctx.arc(pos[0],pos[1],8,0,Math.PI*2);ctx.fillStyle="red";ctx.fill()};ARController.getUserMedia=function(configuration){var facing=configuration.facingMode||"environment";var onSuccess=configuration.onSuccess;var onError=configuration.onError||function(err){console.error("ARController.getUserMedia",err)};var video=document.createElement("video");var initProgress=function(){if(this.videoWidth!==0){onSuccess(video)}};var readyToPlay=false;var eventNames=["touchstart","touchend","touchmove","touchcancel","click","mousedown","mouseup","mousemove","keydown","keyup","keypress","scroll"];var play=function(ev){if(readyToPlay){video.play();if(!video.paused){eventNames.forEach(function(eventName){window.removeEventListener(eventName,play,true)})}}};eventNames.forEach(function(eventName){window.addEventListener(eventName,play,true);
});var success=function(stream){video.addEventListener("loadedmetadata",initProgress,false);video.src=window.URL.createObjectURL(stream);readyToPlay=true;play()};var constraints={};var mediaDevicesConstraints={};if(configuration.width){mediaDevicesConstraints.width=configuration.width;if(typeof configuration.width==="object"){if(configuration.width.max){constraints.maxWidth=configuration.width.max}if(configuration.width.min){constraints.minWidth=configuration.width.max}}else{constraints.maxWidth=configuration.width}}if(configuration.height){mediaDevicesConstraints.height=configuration.height;if(typeof configuration.height==="object"){if(configuration.height.max){constraints.maxHeight=configuration.height.max}if(configuration.height.min){constraints.minHeight=configuration.height.max}}else{constraints.maxHeight=configuration.height}}mediaDevicesConstraints.facingMode=facing;navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var hdConstraints={audio:false,video:{mandatory:constraints}};if(false){if(navigator.mediaDevices){navigator.mediaDevices.getUserMedia({audio:false,video:mediaDevicesConstraints}).then(success,onError)}else{MediaStreamTrack.getSources(function(sources){var facingDir=mediaDevicesConstraints.facingMode;if(facing&&facing.exact){facingDir=facing.exact}for(var i=0;i<sources.length;i++){if(sources[i].kind==="video"&&sources[i].facing===facingDir){hdConstraints.video.mandatory.sourceId=sources[i].id;break}}if(facing&&facing.exact&&!hdConstraints.video.mandatory.sourceId){onError("Failed to get camera facing the wanted direction")}else{if(navigator.getUserMedia){navigator.getUserMedia(hdConstraints,success,onError)}else{onError("navigator.getUserMedia is not supported on your browser")}}})}}else{if(navigator.getUserMedia){navigator.getUserMedia(hdConstraints,success,onError)}else{onError("navigator.getUserMedia is not supported on your browser")}}return video};ARController.getUserMediaARController=function(configuration){var obj={};for(var i in configuration){obj[i]=configuration[i]}var onSuccess=configuration.onSuccess;var cameraParamURL=configuration.cameraParam;obj.onSuccess=function(){new ARCameraParam(cameraParamURL,function(){var arCameraParam=this;var maxSize=configuration.maxARVideoSize||Math.max(video.videoWidth,video.videoHeight);var f=maxSize/Math.max(video.videoWidth,video.videoHeight);var w=f*video.videoWidth;var h=f*video.videoHeight;if(video.videoWidth<video.videoHeight){var tmp=w;w=h;h=tmp}var arController=new ARController(w,h,arCameraParam);arController.image=video;if(video.videoWidth<video.videoHeight){arController.orientation="portrait";arController.videoWidth=video.videoHeight;arController.videoHeight=video.videoWidth}else{arController.orientation="landscape";arController.videoWidth=video.videoWidth;arController.videoHeight=video.videoHeight}onSuccess(arController,arCameraParam)},function(err){console.error("ARController: Failed to load ARCameraParam",err)})};var video=this.getUserMedia(obj);return video};var ARCameraParam=function(src,onload,onerror){this.id=-1;this._src="";this.complete=false;this.onload=onload;this.onerror=onerror;if(src){this.load(src)}};ARCameraParam.prototype.load=function(src){if(this._src!==""){throw"ARCameraParam: Trying to load camera parameters twice."}this._src=src;if(src){var self=this;artoolkit.loadCamera(src,function(id){self.id=id;self.complete=true;self.onload()},function(err){self.onerror(err)})}};Object.defineProperty(ARCameraParam.prototype,"src",{set:function(src){this.load(src)},get:function(){return this._src}});ARCameraParam.prototype.dispose=function(){if(this.id!==-1){artoolkit.deleteCamera(this.id)}this.id=-1;this._src="";this.complete=false};var artoolkit={UNKNOWN_MARKER:-1,PATTERN_MARKER:0,BARCODE_MARKER:1,loadCamera:loadCamera,addMarker:addMarker,addMultiMarker:addMultiMarker};var FUNCTIONS=["setup","teardown","setLogLevel","getLogLevel","setDebugMode","getDebugMode","getProcessingImage","setMarkerInfoDir","setMarkerInfoVertex","getTransMatSquare","getTransMatSquareCont","getTransMatMultiSquare","getTransMatMultiSquareRobust","getMultiMarkerNum","getMultiMarkerCount","detectMarker","getMarkerNum","getMarker","getMultiEachMarker","setProjectionNearPlane","getProjectionNearPlane","setProjectionFarPlane","getProjectionFarPlane","setThresholdMode","getThresholdMode","setThreshold","getThreshold","setPatternDetectionMode","getPatternDetectionMode","setMatrixCodeType","getMatrixCodeType","setLabelingMode","getLabelingMode","setPattRatio","getPattRatio","setImageProcMode","getImageProcMode"];function runWhenLoaded(){FUNCTIONS.forEach(function(n){artoolkit[n]=Module[n]});for(var m in Module){if(m.match(/^AR/))artoolkit[m]=Module[m]}}var marker_count=0;function addMarker(arId,url,callback){var filename="/marker_"+marker_count++;ajax(url,filename,function(){var id=Module._addMarker(arId,filename);if(callback)callback(id)})}function bytesToString(array){return String.fromCharCode.apply(String,array)}function parseMultiFile(bytes){var str=bytesToString(bytes);var lines=str.split("\n");var files=[];var state=0;var markers=0;lines.forEach(function(line){line=line.trim();if(!line||line.startsWith("#"))return;switch(state){case 0:markers=+line;state=1;return;case 1:if(!line.match(/^\d+$/)){files.push(line)}case 2:case 3:case 4:state++;return;case 5:state=1;return}});return files}var multi_marker_count=0;function addMultiMarker(arId,url,callback){var filename="/multi_marker_"+multi_marker_count++;ajax(url,filename,function(bytes){var files=parseMultiFile(bytes);function ok(){var markerID=Module._addMultiMarker(arId,filename);var markerNum=Module.getMultiMarkerNum(arId,markerID);if(callback)callback(markerID,markerNum)}if(!files.length)return ok();var path=url.split("/").slice(0,-1).join("/");files=files.map(function(file){if(file==="patt.hiro"||file==="patt.kanji"||file==="patt2.hiro"||file==="patt2.kanji"){return["http://127.0.0.1:8080/data/data/"+file,file]}return[path+"/"+file,file]});ajaxDependencies(files,ok)})}var camera_count=0;function loadCamera(url,callback){var filename="/camera_param_"+camera_count++;var writeCallback=function(){var id=Module._loadCamera(filename);if(callback)callback(id)};if(typeof url==="object"){writeByteArrayToFS(filename,url,writeCallback)}else if(url.indexOf("\n")>-1){writeStringToFS(filename,url,writeCallback)}else{ajax(url,filename,writeCallback)}}function writeStringToFS(target,string,callback){var byteArray=new Uint8Array(string.length);for(var i=0;i<byteArray.length;i++){byteArray[i]=string.charCodeAt(i)&255}writeByteArrayToFS(target,byteArray,callback)}function writeByteArrayToFS(target,byteArray,callback){FS.writeFile(target,byteArray,{encoding:"binary"});callback(byteArray)}function ajax(url,target,callback){var oReq=new XMLHttpRequest;oReq.open("GET",url,true);oReq.responseType="arraybuffer";oReq.onload=function(oEvent){var arrayBuffer=oReq.response;var byteArray=new Uint8Array(arrayBuffer);writeByteArrayToFS(target,byteArray,callback)};oReq.send()}function ajaxDependencies(files,callback){var next=files.pop();if(next){ajax(next[0],next[1],function(){ajaxDependencies(files,callback)})}else{callback()}}window.artoolkit=artoolkit;window.ARController=ARController;window.ARCameraParam=ARCameraParam;if(window.Module){runWhenLoaded()}else{window.Module={onRuntimeInitialized:function(){runWhenLoaded()}}}})();var AR=AR||{};AR.Marker=function(id,corners){this.id=id;this.corners=corners};AR.Detector=function(){this.grey=new CV.Image;this.thres=new CV.Image;this.homography=new CV.Image;this.binary=[];this.contours=[];this.polys=[];this.candidates=[]};AR.Detector.prototype.detect=function(image){CV.grayscale(image,this.grey);CV.adaptiveThreshold(this.grey,this.thres,2,7);this.contours=CV.findContours(this.thres,this.binary);this.candidates=this.findCandidates(this.contours,image.width*.2,.05,10);this.candidates=this.clockwiseCorners(this.candidates);this.candidates=this.notTooNear(this.candidates,10);return this.findMarkers(this.grey,this.candidates,49)};AR.Detector.prototype.findCandidates=function(contours,minSize,epsilon,minLength){var candidates=[],len=contours.length,contour,poly,i;this.polys=[];for(i=0;i<len;++i){contour=contours[i];if(contour.length>=minSize){poly=CV.approxPolyDP(contour,contour.length*epsilon);this.polys.push(poly);if(4===poly.length&&CV.isContourConvex(poly)){if(CV.minEdgeLength(poly)>=minLength){candidates.push(poly)}}}}return candidates};AR.Detector.prototype.clockwiseCorners=function(candidates){var len=candidates.length,dx1,dx2,dy1,dy2,swap,i;for(i=0;i<len;++i){dx1=candidates[i][1].x-candidates[i][0].x;dy1=candidates[i][1].y-candidates[i][0].y;dx2=candidates[i][2].x-candidates[i][0].x;dy2=candidates[i][2].y-candidates[i][0].y;if(dx1*dy2-dy1*dx2<0){swap=candidates[i][1];candidates[i][1]=candidates[i][3];candidates[i][3]=swap}}return candidates};AR.Detector.prototype.notTooNear=function(candidates,minDist){var notTooNear=[],len=candidates.length,dist,dx,dy,i,j,k;for(i=0;i<len;++i){for(j=i+1;j<len;++j){dist=0;for(k=0;k<4;++k){dx=candidates[i][k].x-candidates[j][k].x;dy=candidates[i][k].y-candidates[j][k].y;dist+=dx*dx+dy*dy}if(dist/4<minDist*minDist){if(CV.perimeter(candidates[i])<CV.perimeter(candidates[j])){candidates[i].tooNear=true}else{candidates[j].tooNear=true}}}}for(i=0;i<len;++i){if(!candidates[i].tooNear){notTooNear.push(candidates[i])}}return notTooNear};AR.Detector.prototype.findMarkers=function(imageSrc,candidates,warpSize){var markers=[],len=candidates.length,candidate,marker,i;for(i=0;i<len;++i){candidate=candidates[i];CV.warp(imageSrc,this.homography,candidate,warpSize);CV.threshold(this.homography,this.homography,CV.otsu(this.homography));marker=this.getMarker(this.homography,candidate);if(marker){markers.push(marker)}}return markers};AR.Detector.prototype.getMarker=function(imageSrc,candidate){var width=imageSrc.width/7>>>0,minZero=width*width>>1,bits=[],rotations=[],distances=[],square,pair,inc,i,j;for(i=0;i<7;++i){inc=0===i||6===i?1:6;for(j=0;j<7;j+=inc){square={x:j*width,y:i*width,width:width,height:width};if(CV.countNonZero(imageSrc,square)>minZero){return null}}}for(i=0;i<5;++i){bits[i]=[];for(j=0;j<5;++j){square={x:(j+1)*width,y:(i+1)*width,width:width,height:width};bits[i][j]=CV.countNonZero(imageSrc,square)>minZero?1:0}}rotations[0]=bits;distances[0]=this.hammingDistance(rotations[0]);pair={first:distances[0],second:0};for(i=1;i<4;++i){rotations[i]=this.rotate(rotations[i-1]);distances[i]=this.hammingDistance(rotations[i]);if(distances[i]<pair.first){pair.first=distances[i];pair.second=i}}if(0!==pair.first){return null}return new AR.Marker(this.mat2id(rotations[pair.second]),this.rotate2(candidate,4-pair.second))};AR.Detector.prototype.hammingDistance=function(bits){var ids=[[1,0,0,0,0],[1,0,1,1,1],[0,1,0,0,1],[0,1,1,1,0]],dist=0,sum,minSum,i,j,k;for(i=0;i<5;++i){minSum=Infinity;for(j=0;j<4;++j){sum=0;for(k=0;k<5;++k){sum+=bits[i][k]===ids[j][k]?0:1}if(sum<minSum){minSum=sum}}dist+=minSum}return dist};AR.Detector.prototype.mat2id=function(bits){var id=0,i;for(i=0;i<5;++i){id<<=1;id|=bits[i][1];id<<=1;id|=bits[i][3]}return id};AR.Detector.prototype.rotate=function(src){var dst=[],len=src.length,i,j;for(i=0;i<len;++i){dst[i]=[];for(j=0;j<src[i].length;++j){dst[i][j]=src[src[i].length-j-1][i]}}return dst};AR.Detector.prototype.rotate2=function(src,rotation){var dst=[],len=src.length,i;for(i=0;i<len;++i){dst[i]=src[(rotation+i)%len]}return dst};var CV=CV||{};CV.Image=function(width,height,data){this.width=width||0;this.height=height||0;this.data=data||[]};CV.grayscale=function(imageSrc,imageDst){var src=imageSrc.data,dst=imageDst.data,len=src.length,i=0,j=0;for(;i<len;i+=4){dst[j++]=src[i]*.299+src[i+1]*.587+src[i+2]*.114+.5&255}imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;return imageDst};CV.threshold=function(imageSrc,imageDst,threshold){var src=imageSrc.data,dst=imageDst.data,len=src.length,tab=[],i;for(i=0;i<256;++i){tab[i]=i<=threshold?0:255}for(i=0;i<len;++i){dst[i]=tab[src[i]]}imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;return imageDst};CV.adaptiveThreshold=function(imageSrc,imageDst,kernelSize,threshold){var src=imageSrc.data,dst=imageDst.data,len=src.length,tab=[],i;CV.stackBoxBlur(imageSrc,imageDst,kernelSize);for(i=0;i<768;++i){tab[i]=i-255<=-threshold?255:0}for(i=0;i<len;++i){dst[i]=tab[src[i]-dst[i]+255]}imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;return imageDst};CV.otsu=function(imageSrc){var src=imageSrc.data,len=src.length,hist=[],threshold=0,sum=0,sumB=0,wB=0,wF=0,max=0,mu,between,i;for(i=0;i<256;++i){hist[i]=0}for(i=0;i<len;++i){hist[src[i]]++}for(i=0;i<256;++i){sum+=hist[i]*i}for(i=0;i<256;++i){wB+=hist[i];if(0!==wB){wF=len-wB;if(0===wF){break}sumB+=hist[i]*i;mu=sumB/wB-(sum-sumB)/wF;between=wB*wF*mu*mu;if(between>max){max=between;threshold=i}}}return threshold};CV.stackBoxBlurMult=[1,171,205,293,57,373,79,137,241,27,391,357,41,19,283,265];CV.stackBoxBlurShift=[0,9,10,11,9,12,10,11,12,9,13,13,10,9,13,13];CV.BlurStack=function(){this.color=0;this.next=null};CV.stackBoxBlur=function(imageSrc,imageDst,kernelSize){var src=imageSrc.data,dst=imageDst.data,height=imageSrc.height,width=imageSrc.width,heightMinus1=height-1,widthMinus1=width-1,size=kernelSize+kernelSize+1,radius=kernelSize+1,mult=CV.stackBoxBlurMult[kernelSize],shift=CV.stackBoxBlurShift[kernelSize],stack,stackStart,color,sum,pos,start,p,x,y,i;stack=stackStart=new CV.BlurStack;for(i=1;i<size;++i){stack=stack.next=new CV.BlurStack}stack.next=stackStart;pos=0;for(y=0;y<height;++y){start=pos;color=src[pos];sum=radius*color;stack=stackStart;for(i=0;i<radius;++i){stack.color=color;stack=stack.next}for(i=1;i<radius;++i){stack.color=src[pos+i];sum+=stack.color;stack=stack.next}stack=stackStart;for(x=0;x<width;++x){dst[pos++]=sum*mult>>>shift;p=x+radius;p=start+(p<widthMinus1?p:widthMinus1);sum-=stack.color-src[p];stack.color=src[p];stack=stack.next}}for(x=0;x<width;++x){pos=x;start=pos+width;color=dst[pos];sum=radius*color;stack=stackStart;for(i=0;i<radius;++i){stack.color=color;stack=stack.next}for(i=1;i<radius;++i){stack.color=dst[start];sum+=stack.color;stack=stack.next;start+=width}stack=stackStart;for(y=0;y<height;++y){dst[pos]=sum*mult>>>shift;p=y+radius;p=x+(p<heightMinus1?p:heightMinus1)*width;sum-=stack.color-dst[p];stack.color=dst[p];stack=stack.next;pos+=width}}return imageDst};CV.gaussianBlur=function(imageSrc,imageDst,imageMean,kernelSize){var kernel=CV.gaussianKernel(kernelSize);imageDst.width=imageSrc.width;imageDst.height=imageSrc.height;imageMean.width=imageSrc.width;imageMean.height=imageSrc.height;CV.gaussianBlurFilter(imageSrc,imageMean,kernel,true);CV.gaussianBlurFilter(imageMean,imageDst,kernel,false);return imageDst};CV.gaussianBlurFilter=function(imageSrc,imageDst,kernel,horizontal){var src=imageSrc.data,dst=imageDst.data,height=imageSrc.height,width=imageSrc.width,pos=0,limit=kernel.length>>1,cur,value,i,j,k;for(i=0;i<height;++i){for(j=0;j<width;++j){value=0;for(k=-limit;k<=limit;++k){if(horizontal){cur=pos+k;if(j+k<0){cur=pos}else if(j+k>=width){cur=pos}}else{cur=pos+k*width;if(i+k<0){cur=pos}else if(i+k>=height){cur=pos}}value+=kernel[limit+k]*src[cur]}dst[pos++]=horizontal?value:value+.5&255}}return imageDst};CV.gaussianKernel=function(kernelSize){var tab=[[1],[.25,.5,.25],[.0625,.25,.375,.25,.0625],[.03125,.109375,.21875,.28125,.21875,.109375,.03125]],kernel=[],center,sigma,scale2X,sum,x,i;if(kernelSize<=7&&kernelSize%2===1){kernel=tab[kernelSize>>1]}else{center=(kernelSize-1)*.5;sigma=.8+.3*(center-1);scale2X=-.5/(sigma*sigma);sum=0;for(i=0;i<kernelSize;++i){x=i-center;sum+=kernel[i]=Math.exp(scale2X*x*x)}sum=1/sum;for(i=0;i<kernelSize;++i){kernel[i]*=sum}}return kernel};CV.findContours=function(imageSrc,binary){var width=imageSrc.width,height=imageSrc.height,contours=[],src,deltas,pos,pix,nbd,outer,hole,i,j;src=CV.binaryBorder(imageSrc,binary);deltas=CV.neighborhoodDeltas(width+2);pos=width+3;nbd=1;for(i=0;i<height;++i,pos+=2){for(j=0;j<width;++j,++pos){pix=src[pos];if(0!==pix){outer=hole=false;if(1===pix&&0===src[pos-1]){outer=true}else if(pix>=1&&0===src[pos+1]){hole=true}if(outer||hole){++nbd;contours.push(CV.borderFollowing(src,pos,nbd,{x:j,y:i},hole,deltas))}}}}return contours};CV.borderFollowing=function(src,pos,nbd,point,hole,deltas){var contour=[],pos1,pos3,pos4,s,s_end,s_prev;contour.hole=hole;s=s_end=hole?0:4;do{s=s-1&7;pos1=pos+deltas[s];if(src[pos1]!==0){break}}while(s!==s_end);if(s===s_end){src[pos]=-nbd;contour.push({x:point.x,y:point.y})}else{pos3=pos;s_prev=s^4;while(true){s_end=s;do{pos4=pos3+deltas[++s]}while(src[pos4]===0);s&=7;if(s-1>>>0<s_end>>>0){src[pos3]=-nbd}else if(src[pos3]===1){src[pos3]=nbd}contour.push({x:point.x,y:point.y});s_prev=s;point.x+=CV.neighborhood[s][0];point.y+=CV.neighborhood[s][1];if(pos4===pos&&pos3===pos1){break}pos3=pos4;s=s+4&7}}return contour};CV.neighborhood=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1]];CV.neighborhoodDeltas=function(width){var deltas=[],len=CV.neighborhood.length,i=0;for(;i<len;++i){deltas[i]=CV.neighborhood[i][0]+CV.neighborhood[i][1]*width}return deltas.concat(deltas)};CV.approxPolyDP=function(contour,epsilon){var slice={start_index:0,end_index:0},right_slice={start_index:0,end_index:0},poly=[],stack=[],len=contour.length,pt,start_pt,end_pt,dist,max_dist,le_eps,dx,dy,i,j,k;epsilon*=epsilon;k=0;for(i=0;i<3;++i){max_dist=0;k=(k+right_slice.start_index)%len;start_pt=contour[k];if(++k===len){k=0}for(j=1;j<len;++j){pt=contour[k];if(++k===len){k=0}dx=pt.x-start_pt.x;dy=pt.y-start_pt.y;dist=dx*dx+dy*dy;if(dist>max_dist){max_dist=dist;right_slice.start_index=j}}}if(max_dist<=epsilon){poly.push({x:start_pt.x,y:start_pt.y})}else{slice.start_index=k;slice.end_index=right_slice.start_index+=slice.start_index;right_slice.start_index-=right_slice.start_index>=len?len:0;right_slice.end_index=slice.start_index;if(right_slice.end_index<right_slice.start_index){right_slice.end_index+=len}stack.push({start_index:right_slice.start_index,end_index:right_slice.end_index});stack.push({start_index:slice.start_index,end_index:slice.end_index})}while(stack.length!==0){slice=stack.pop();end_pt=contour[slice.end_index%len];start_pt=contour[k=slice.start_index%len];if(++k===len){k=0}if(slice.end_index<=slice.start_index+1){le_eps=true}else{max_dist=0;dx=end_pt.x-start_pt.x;dy=end_pt.y-start_pt.y;for(i=slice.start_index+1;i<slice.end_index;++i){pt=contour[k];if(++k===len){k=0}dist=Math.abs((pt.y-start_pt.y)*dx-(pt.x-start_pt.x)*dy);if(dist>max_dist){max_dist=dist;right_slice.start_index=i}}le_eps=max_dist*max_dist<=epsilon*(dx*dx+dy*dy)}if(le_eps){poly.push({x:start_pt.x,y:start_pt.y})}else{right_slice.end_index=slice.end_index;slice.end_index=right_slice.start_index;stack.push({start_index:right_slice.start_index,end_index:right_slice.end_index});stack.push({start_index:slice.start_index,end_index:slice.end_index})}}return poly};CV.warp=function(imageSrc,imageDst,contour,warpSize){var src=imageSrc.data,dst=imageDst.data,width=imageSrc.width,height=imageSrc.height,pos=0,sx1,sx2,dx1,dx2,sy1,sy2,dy1,dy2,p1,p2,p3,p4,m,r,s,t,u,v,w,x,y,i,j;m=CV.getPerspectiveTransform(contour,warpSize-1);r=m[8];s=m[2];t=m[5];for(i=0;i<warpSize;++i){r+=m[7];s+=m[1];t+=m[4];u=r;v=s;w=t;for(j=0;j<warpSize;++j){u+=m[6];v+=m[0];w+=m[3];x=v/u;y=w/u;sx1=x>>>0;sx2=sx1===width-1?sx1:sx1+1;dx1=x-sx1;dx2=1-dx1;sy1=y>>>0;sy2=sy1===height-1?sy1:sy1+1;dy1=y-sy1;dy2=1-dy1;p1=p2=sy1*width;p3=p4=sy2*width;dst[pos++]=dy2*(dx2*src[p1+sx1]+dx1*src[p2+sx2])+dy1*(dx2*src[p3+sx1]+dx1*src[p4+sx2])&255}}imageDst.width=warpSize;imageDst.height=warpSize;return imageDst};CV.getPerspectiveTransform=function(src,size){var rq=CV.square2quad(src);rq[0]/=size;rq[1]/=size;rq[3]/=size;rq[4]/=size;rq[6]/=size;rq[7]/=size;return rq};CV.square2quad=function(src){var sq=[],px,py,dx1,dx2,dy1,dy2,den;px=src[0].x-src[1].x+src[2].x-src[3].x;py=src[0].y-src[1].y+src[2].y-src[3].y;if(0===px&&0===py){sq[0]=src[1].x-src[0].x;sq[1]=src[2].x-src[1].x;sq[2]=src[0].x;sq[3]=src[1].y-src[0].y;sq[4]=src[2].y-src[1].y;sq[5]=src[0].y;sq[6]=0;sq[7]=0;sq[8]=1}else{dx1=src[1].x-src[2].x;dx2=src[3].x-src[2].x;dy1=src[1].y-src[2].y;dy2=src[3].y-src[2].y;den=dx1*dy2-dx2*dy1;sq[6]=(px*dy2-dx2*py)/den;sq[7]=(dx1*py-px*dy1)/den;sq[8]=1;sq[0]=src[1].x-src[0].x+sq[6]*src[1].x;sq[1]=src[3].x-src[0].x+sq[7]*src[3].x;sq[2]=src[0].x;sq[3]=src[1].y-src[0].y+sq[6]*src[1].y;sq[4]=src[3].y-src[0].y+sq[7]*src[3].y;sq[5]=src[0].y}return sq};CV.isContourConvex=function(contour){var orientation=0,convex=true,len=contour.length,i=0,j=0,cur_pt,prev_pt,dxdy0,dydx0,dx0,dy0,dx,dy;prev_pt=contour[len-1];cur_pt=contour[0];dx0=cur_pt.x-prev_pt.x;dy0=cur_pt.y-prev_pt.y;for(;i<len;++i){if(++j===len){j=0}prev_pt=cur_pt;cur_pt=contour[j];dx=cur_pt.x-prev_pt.x;dy=cur_pt.y-prev_pt.y;dxdy0=dx*dy0;dydx0=dy*dx0;orientation|=dydx0>dxdy0?1:dydx0<dxdy0?2:3;if(3===orientation){convex=false;break}dx0=dx;dy0=dy}return convex};CV.perimeter=function(poly){var len=poly.length,i=0,j=len-1,p=0,dx,dy;for(;i<len;j=i++){dx=poly[i].x-poly[j].x;dy=poly[i].y-poly[j].y;p+=Math.sqrt(dx*dx+dy*dy)}return p};CV.minEdgeLength=function(poly){var len=poly.length,i=0,j=len-1,min=Infinity,d,dx,dy;for(;i<len;j=i++){dx=poly[i].x-poly[j].x;dy=poly[i].y-poly[j].y;d=dx*dx+dy*dy;if(d<min){min=d}}return Math.sqrt(min)};CV.countNonZero=function(imageSrc,square){var src=imageSrc.data,height=square.height,width=square.width,pos=square.x+square.y*imageSrc.width,span=imageSrc.width-width,nz=0,i,j;for(i=0;i<height;++i){for(j=0;j<width;++j){if(0!==src[pos++]){++nz}}pos+=span}return nz};CV.binaryBorder=function(imageSrc,dst){var src=imageSrc.data,height=imageSrc.height,width=imageSrc.width,posSrc=0,posDst=0,i,j;for(j=-2;j<width;++j){dst[posDst++]=0}for(i=0;i<height;++i){dst[posDst++]=0;for(j=0;j<width;++j){dst[posDst++]=0===src[posSrc++]?0:1}dst[posDst++]=0}for(j=-2;j<width;++j){dst[posDst++]=0}return dst};var POS=POS||{};POS.Posit=function(modelSize,focalLength){this.objectPoints=this.buildModel(modelSize);this.focalLength=focalLength;this.objectVectors=[];this.objectNormal=[];this.objectMatrix=[[],[],[]];this.init()};POS.Posit.prototype.buildModel=function(modelSize){var half=modelSize/2;return[[-half,half,0],[half,half,0],[half,-half,0],[-half,-half,0]]};POS.Posit.prototype.init=function(){var np=this.objectPoints.length,vectors=[],n=[],len=0,row=2,i;for(i=0;i<np;++i){this.objectVectors[i]=[this.objectPoints[i][0]-this.objectPoints[0][0],this.objectPoints[i][1]-this.objectPoints[0][1],this.objectPoints[i][2]-this.objectPoints[0][2]];vectors[i]=[this.objectVectors[i][0],this.objectVectors[i][1],this.objectVectors[i][2]]}while(0===len){n[0]=this.objectVectors[1][1]*this.objectVectors[row][2]-this.objectVectors[1][2]*this.objectVectors[row][1];n[1]=this.objectVectors[1][2]*this.objectVectors[row][0]-this.objectVectors[1][0]*this.objectVectors[row][2];n[2]=this.objectVectors[1][0]*this.objectVectors[row][1]-this.objectVectors[1][1]*this.objectVectors[row][0];len=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);++row}for(i=0;i<3;++i){this.objectNormal[i]=n[i]/len}POS.pseudoInverse(vectors,np,this.objectMatrix)};POS.Posit.prototype.pose=function(imagePoints){var posRotation1=[[],[],[]],posRotation2=[[],[],[]],posTranslation=[],rotation1=[[],[],[]],rotation2=[[],[],[]],translation1=[],translation2=[],error1,error2,valid1,valid2,i,j;this.pos(imagePoints,posRotation1,posRotation2,posTranslation);valid1=this.isValid(posRotation1,posTranslation);if(valid1){error1=this.iterate(imagePoints,posRotation1,posTranslation,rotation1,translation1)}else{error1={euclidean:-1,pixels:-1,maximum:-1}}valid2=this.isValid(posRotation2,posTranslation);if(valid2){error2=this.iterate(imagePoints,posRotation2,posTranslation,rotation2,translation2)}else{error2={euclidean:-1,pixels:-1,maximum:-1}}for(i=0;i<3;++i){for(j=0;j<3;++j){if(valid1){translation1[i]-=rotation1[i][j]*this.objectPoints[0][j]}if(valid2){translation2[i]-=rotation2[i][j]*this.objectPoints[0][j]}}}return error1.euclidean<error2.euclidean?new POS.Pose(error1.pixels,rotation1,translation1,error2.pixels,rotation2,translation2):new POS.Pose(error2.pixels,rotation2,translation2,error1.pixels,rotation1,translation1)};POS.Posit.prototype.pos=function(imagePoints,rotation1,rotation2,translation){var np=this.objectPoints.length,imageVectors=[],i0=[],j0=[],ivec=[],jvec=[],row1=[],row2=[],row3=[],i0i0,j0j0,i0j0,delta,q,lambda,mu,scale,i,j;for(i=0;i<np;++i){imageVectors[i]=[imagePoints[i].x-imagePoints[0].x,imagePoints[i].y-imagePoints[0].y]}for(i=0;i<3;++i){i0[i]=0;j0[i]=0;for(j=0;j<np;++j){i0[i]+=this.objectMatrix[i][j]*imageVectors[j][0];j0[i]+=this.objectMatrix[i][j]*imageVectors[j][1]}}i0i0=i0[0]*i0[0]+i0[1]*i0[1]+i0[2]*i0[2];j0j0=j0[0]*j0[0]+j0[1]*j0[1]+j0[2]*j0[2];i0j0=i0[0]*j0[0]+i0[1]*j0[1]+i0[2]*j0[2];delta=(j0j0-i0i0)*(j0j0-i0i0)+4*(i0j0*i0j0);if(j0j0-i0i0>=0){q=(j0j0-i0i0+Math.sqrt(delta))/2}else{q=(j0j0-i0i0-Math.sqrt(delta))/2}if(q>=0){lambda=Math.sqrt(q);if(0===lambda){mu=0}else{mu=-i0j0/lambda}}else{lambda=Math.sqrt(-(i0j0*i0j0)/q);if(0===lambda){mu=Math.sqrt(i0i0-j0j0)}else{mu=-i0j0/lambda}}for(i=0;i<3;++i){ivec[i]=i0[i]+lambda*this.objectNormal[i];jvec[i]=j0[i]+mu*this.objectNormal[i]}scale=Math.sqrt(ivec[0]*ivec[0]+ivec[1]*ivec[1]+ivec[2]*ivec[2]);for(i=0;i<3;++i){row1[i]=ivec[i]/scale;row2[i]=jvec[i]/scale}row3[0]=row1[1]*row2[2]-row1[2]*row2[1];row3[1]=row1[2]*row2[0]-row1[0]*row2[2];row3[2]=row1[0]*row2[1]-row1[1]*row2[0];for(i=0;i<3;++i){rotation1[0][i]=row1[i];rotation1[1][i]=row2[i];rotation1[2][i]=row3[i]}for(i=0;i<3;++i){ivec[i]=i0[i]-lambda*this.objectNormal[i];jvec[i]=j0[i]-mu*this.objectNormal[i]}for(i=0;i<3;++i){row1[i]=ivec[i]/scale;row2[i]=jvec[i]/scale}row3[0]=row1[1]*row2[2]-row1[2]*row2[1];row3[1]=row1[2]*row2[0]-row1[0]*row2[2];row3[2]=row1[0]*row2[1]-row1[1]*row2[0];for(i=0;i<3;++i){rotation2[0][i]=row1[i];rotation2[1][i]=row2[i];rotation2[2][i]=row3[i]}translation[0]=imagePoints[0].x/scale;translation[1]=imagePoints[0].y/scale;translation[2]=this.focalLength/scale};POS.Posit.prototype.isValid=function(rotation,translation){var np=this.objectPoints.length,zmin=Infinity,i=0,zi;for(;i<np;++i){zi=translation[2]+(rotation[2][0]*this.objectVectors[i][0]+rotation[2][1]*this.objectVectors[i][1]+rotation[2][2]*this.objectVectors[i][2]);if(zi<zmin){zmin=zi}}return zmin>=0};POS.Posit.prototype.iterate=function(imagePoints,posRotation,posTranslation,rotation,translation){var np=this.objectPoints.length,oldSopImagePoints=[],sopImagePoints=[],rotation1=[[],[],[]],rotation2=[[],[],[]],translation1=[],translation2=[],converged=false,iteration=0,oldImageDifference,imageDifference,factor,error,error1,error2,delta,i,j;for(i=0;i<np;++i){oldSopImagePoints[i]={x:imagePoints[i].x,y:imagePoints[i].y}}for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=posRotation[i][j]}translation[i]=posTranslation[i]}for(i=0;i<np;++i){factor=0;for(j=0;j<3;++j){factor+=this.objectVectors[i][j]*rotation[2][j]/translation[2]}sopImagePoints[i]={x:(1+factor)*imagePoints[i].x,y:(1+factor)*imagePoints[i].y}}imageDifference=0;for(i=0;i<np;++i){imageDifference+=Math.abs(sopImagePoints[i].x-oldSopImagePoints[i].x);imageDifference+=Math.abs(sopImagePoints[i].y-oldSopImagePoints[i].y)}for(i=0;i<3;++i){translation1[i]=translation[i]-(rotation[i][0]*this.objectPoints[0][0]+rotation[i][1]*this.objectPoints[0][1]+rotation[i][2]*this.objectPoints[0][2])}error=error1=this.error(imagePoints,rotation,translation1);converged=0===error1.pixels||imageDifference<.01;while(iteration++<100&&!converged){for(i=0;i<np;++i){oldSopImagePoints[i].x=sopImagePoints[i].x;oldSopImagePoints[i].y=sopImagePoints[i].y}this.pos(sopImagePoints,rotation1,rotation2,translation);for(i=0;i<3;++i){translation1[i]=translation[i]-(rotation1[i][0]*this.objectPoints[0][0]+rotation1[i][1]*this.objectPoints[0][1]+rotation1[i][2]*this.objectPoints[0][2]);translation2[i]=translation[i]-(rotation2[i][0]*this.objectPoints[0][0]+rotation2[i][1]*this.objectPoints[0][1]+rotation2[i][2]*this.objectPoints[0][2])}error1=this.error(imagePoints,rotation1,translation1);error2=this.error(imagePoints,rotation2,translation2);if(error1.euclidean>=0&&error2.euclidean>=0){if(error2.euclidean<error1.euclidean){error=error2;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation2[i][j]}}}else{error=error1;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation1[i][j]}}}}if(error1.euclidean<0&&error2.euclidean>=0){error=error2;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation2[i][j]}}}if(error2.euclidean<0&&error1.euclidean>=0){error=error1;for(i=0;i<3;++i){for(j=0;j<3;++j){rotation[i][j]=rotation1[i][j]}}}for(i=0;i<np;++i){factor=0;for(j=0;j<3;++j){factor+=this.objectVectors[i][j]*rotation[2][j]/translation[2]}sopImagePoints[i].x=(1+factor)*imagePoints[i].x;sopImagePoints[i].y=(1+factor)*imagePoints[i].y}oldImageDifference=imageDifference;imageDifference=0;for(i=0;i<np;++i){imageDifference+=Math.abs(sopImagePoints[i].x-oldSopImagePoints[i].x);imageDifference+=Math.abs(sopImagePoints[i].y-oldSopImagePoints[i].y)}delta=Math.abs(imageDifference-oldImageDifference);converged=0===error.pixels||delta<.01}return error};POS.Posit.prototype.error=function(imagePoints,rotation,translation){var np=this.objectPoints.length,move=[],projection=[],errorvec=[],euclidean=0,pixels=0,maximum=0,i,j,k;if(!this.isValid(rotation,translation)){return{euclidean:-1,pixels:-1,maximum:-1}}for(i=0;i<np;++i){move[i]=[];for(j=0;j<3;++j){move[i][j]=translation[j]}}for(i=0;i<np;++i){for(j=0;j<3;++j){for(k=0;k<3;++k){move[i][j]+=rotation[j][k]*this.objectPoints[i][k]}}}for(i=0;i<np;++i){projection[i]=[];for(j=0;j<2;++j){projection[i][j]=this.focalLength*move[i][j]/move[i][2]}}for(i=0;i<np;++i){errorvec[i]=[projection[i][0]-imagePoints[i].x,projection[i][1]-imagePoints[i].y]}for(i=0;i<np;++i){euclidean+=Math.sqrt(errorvec[i][0]*errorvec[i][0]+errorvec[i][1]*errorvec[i][1]);pixels+=Math.abs(Math.round(projection[i][0])-Math.round(imagePoints[i].x))+Math.abs(Math.round(projection[i][1])-Math.round(imagePoints[i].y));if(Math.abs(errorvec[i][0])>maximum){maximum=Math.abs(errorvec[i][0])}if(Math.abs(errorvec[i][1])>maximum){maximum=Math.abs(errorvec[i][1])}}return{euclidean:euclidean/np,pixels:pixels,maximum:maximum}};POS.pseudoInverse=function(a,n,b){var w=[],v=[[],[],[]],s=[[],[],[]],wmax=0,cn=0,i,j,k;SVD.svdcmp(a,n,3,w,v);for(i=0;i<3;++i){if(w[i]>wmax){wmax=w[i]}}wmax*=.01;for(i=0;i<3;++i){if(w[i]<wmax){w[i]=0}}for(j=0;j<3;++j){if(0===w[j]){++cn;for(k=j;k<2;++k){for(i=0;i<n;++i){a[i][k]=a[i][k+1]}for(i=0;i<3;++i){v[i][k]=v[i][k+1]}}}}for(j=0;j<2;++j){if(0===w[j]){w[j]=w[j+1]}}for(i=0;i<3;++i){for(j=0;j<3-cn;++j){s[i][j]=v[i][j]/w[j]}}for(i=0;i<3;++i){for(j=0;j<n;++j){b[i][j]=0;for(k=0;k<3-cn;++k){b[i][j]+=s[i][k]*a[j][k]}}}};POS.Pose=function(error1,rotation1,translation1,error2,rotation2,translation2){this.bestError=error1;this.bestRotation=rotation1;this.bestTranslation=translation1;this.alternativeError=error2;this.alternativeRotation=rotation2;this.alternativeTranslation=translation2};var SVD=SVD||{};SVD.svdcmp=function(a,m,n,w,v){var flag,i,its,j,jj,k,l,nm,anorm=0,c,f,g=0,h,s,scale=0,x,y,z,rv1=[];for(i=0;i<n;++i){l=i+1;rv1[i]=scale*g;g=s=scale=0;if(i<m){for(k=i;k<m;++k){scale+=Math.abs(a[k][i])}if(0!==scale){for(k=i;k<m;++k){a[k][i]/=scale;s+=a[k][i]*a[k][i]}f=a[i][i];g=-SVD.sign(Math.sqrt(s),f);h=f*g-s;a[i][i]=f-g;for(j=l;j<n;++j){for(s=0,k=i;k<m;++k){s+=a[k][i]*a[k][j]}f=s/h;for(k=i;k<m;++k){a[k][j]+=f*a[k][i]}}for(k=i;k<m;++k){a[k][i]*=scale}}}w[i]=scale*g;g=s=scale=0;if(i<m&&i!==n-1){for(k=l;k<n;++k){scale+=Math.abs(a[i][k])}if(0!==scale){for(k=l;k<n;++k){a[i][k]/=scale;s+=a[i][k]*a[i][k]}f=a[i][l];g=-SVD.sign(Math.sqrt(s),f);h=f*g-s;a[i][l]=f-g;for(k=l;k<n;++k){rv1[k]=a[i][k]/h}for(j=l;j<m;++j){for(s=0,k=l;k<n;++k){s+=a[j][k]*a[i][k]}for(k=l;k<n;++k){a[j][k]+=s*rv1[k]}}for(k=l;k<n;++k){a[i][k]*=scale}}}anorm=Math.max(anorm,Math.abs(w[i])+Math.abs(rv1[i]))}for(i=n-1;i>=0;--i){if(i<n-1){if(0!==g){for(j=l;j<n;++j){v[j][i]=a[i][j]/a[i][l]/g}for(j=l;j<n;++j){for(s=0,k=l;k<n;++k){s+=a[i][k]*v[k][j];
}for(k=l;k<n;++k){v[k][j]+=s*v[k][i]}}}for(j=l;j<n;++j){v[i][j]=v[j][i]=0}}v[i][i]=1;g=rv1[i];l=i}for(i=Math.min(n,m)-1;i>=0;--i){l=i+1;g=w[i];for(j=l;j<n;++j){a[i][j]=0}if(0!==g){g=1/g;for(j=l;j<n;++j){for(s=0,k=l;k<m;++k){s+=a[k][i]*a[k][j]}f=s/a[i][i]*g;for(k=i;k<m;++k){a[k][j]+=f*a[k][i]}}for(j=i;j<m;++j){a[j][i]*=g}}else{for(j=i;j<m;++j){a[j][i]=0}}++a[i][i]}for(k=n-1;k>=0;--k){for(its=1;its<=30;++its){flag=true;for(l=k;l>=0;--l){nm=l-1;if(Math.abs(rv1[l])+anorm===anorm){flag=false;break}if(Math.abs(w[nm])+anorm===anorm){break}}if(flag){c=0;s=1;for(i=l;i<=k;++i){f=s*rv1[i];if(Math.abs(f)+anorm===anorm){break}g=w[i];h=SVD.pythag(f,g);w[i]=h;h=1/h;c=g*h;s=-f*h;for(j=1;j<=m;++j){y=a[j][nm];z=a[j][i];a[j][nm]=y*c+z*s;a[j][i]=z*c-y*s}}}z=w[k];if(l===k){if(z<0){w[k]=-z;for(j=0;j<n;++j){v[j][k]=-v[j][k]}}break}if(30===its){return false}x=w[l];nm=k-1;y=w[nm];g=rv1[nm];h=rv1[k];f=((y-z)*(y+z)+(g-h)*(g+h))/(2*h*y);g=SVD.pythag(f,1);f=((x-z)*(x+z)+h*(y/(f+SVD.sign(g,f))-h))/x;c=s=1;for(j=l;j<=nm;++j){i=j+1;g=rv1[i];y=w[i];h=s*g;g=c*g;z=SVD.pythag(f,h);rv1[j]=z;c=f/z;s=h/z;f=x*c+g*s;g=g*c-x*s;h=y*s;y*=c;for(jj=0;jj<n;++jj){x=v[jj][j];z=v[jj][i];v[jj][j]=x*c+z*s;v[jj][i]=z*c-x*s}z=SVD.pythag(f,h);w[j]=z;if(0!==z){z=1/z;c=f*z;s=h*z}f=c*g+s*y;x=c*y-s*g;for(jj=0;jj<m;++jj){y=a[jj][j];z=a[jj][i];a[jj][j]=y*c+z*s;a[jj][i]=z*c-y*s}}rv1[l]=0;rv1[k]=f;w[k]=x}}return true};SVD.pythag=function(a,b){var at=Math.abs(a),bt=Math.abs(b),ct;if(at>bt){ct=bt/at;return at*Math.sqrt(1+ct*ct)}if(0===bt){return 0}ct=at/bt;return bt*Math.sqrt(1+ct*ct)};SVD.sign=function(a,b){return b>=0?Math.abs(a):-Math.abs(a)};var THREEx=THREEx||{};THREEx.ArucoContext=function(parameters){parameters=parameters||{};this.parameters={debug:parameters.debug!==undefined?parameters.debug:false,canvasWidth:parameters.canvasWidth!==undefined?parameters.canvasWidth:640,canvasHeight:parameters.canvasHeight!==undefined?parameters.canvasHeight:480};this.canvas=document.createElement("canvas");this.detector=new AR.Detector;this.debug=null;if(parameters.debug==true){this.debug=new THREEx.ArucoDebug(this)}this.setSize(this.parameters.canvasWidth,this.parameters.canvasHeight)};THREEx.ArucoContext.prototype.setSize=function(width,height){this.canvas.width=width;this.canvas.height=height;if(this.debug!==null){this.debug.setSize(width,height)}};THREEx.ArucoContext.prototype.detect=function(videoElement){var _this=this;var canvas=this.canvas;var context=canvas.getContext("2d");context.drawImage(videoElement,0,0,canvas.width,canvas.height);var imageData=context.getImageData(0,0,canvas.width,canvas.height);var detectedMarkers=this.detector.detect(imageData);return detectedMarkers};THREEx.ArucoContext.prototype.updateObject3D=function(object3D,arucoPosit,markerSize,detectedMarker){var markerCorners=detectedMarker.corners;var canvas=this.canvas;var poseCorners=new Array(markerCorners.length);for(var i=0;i<markerCorners.length;++i){var markerCorner=markerCorners[i];poseCorners[i]={x:markerCorner.x-canvas.width/2,y:-markerCorner.y+canvas.height/2}}var pose=arucoPosit.pose(poseCorners);var rotation=pose.bestRotation;var translation=pose.bestTranslation;object3D.position.x=translation[0];object3D.position.y=translation[1];object3D.position.z=-translation[2];object3D.rotation.x=-Math.asin(-rotation[1][2]);object3D.rotation.y=-Math.atan2(rotation[0][2],rotation[2][2]);object3D.rotation.z=Math.atan2(rotation[1][0],rotation[1][1]);object3D.scale.x=markerSize;object3D.scale.y=markerSize;object3D.scale.z=markerSize};var THREEx=THREEx||{};AR.Detector.prototype.detect=function(image){var opts=this.datGUIOptions;CV.grayscale(image,this.grey);CV.adaptiveThreshold(this.grey,this.thres,opts.adaptativeThreshold.kernelSize,opts.adaptativeThreshold.threshold);this.contours=CV.findContours(this.thres,this.binary);this.candidates=this.findCandidates(this.contours,image.width*opts.candidates.minSize,opts.candidates.epsilon,opts.candidates.minLength);this.candidates=this.clockwiseCorners(this.candidates);this.candidates=this.notTooNear(this.candidates,opts.notTooNear.minDist);return this.findMarkers(this.grey,this.candidates,opts.findMarkers.warpSize)};AR.Detector.prototype.datGUIOptions={adaptativeThreshold:{kernelSize:2,threshold:7},candidates:{minSize:.2,epsilon:.05,minLength:10},notTooNear:{minDist:10},findMarkers:{warpSize:49}};THREEx.addArucoDatGui=function(arucoContext,datGui){var datGUIOptions=arucoContext.detector.datGUIOptions;var options={resolution:"640x480"};var onChange=function(){var matches=options.resolution.match(/(\d+)x(\d+)/);var width=parseInt(matches[1]);var height=parseInt(matches[2]);arucoContext.setSize(width,height)};onChange();datGui.add(options,"resolution",["320x240","640x480"]).onChange(onChange);var folder=datGui.addFolder("Adaptative Threshold");folder.open();folder.add(arucoContext.detector.datGUIOptions.adaptativeThreshold,"kernelSize").min(0).step(1).onChange(onChange);folder.add(arucoContext.detector.datGUIOptions.adaptativeThreshold,"threshold").min(0).step(1).onChange(onChange);var folder=datGui.addFolder("Candidates");folder.open();folder.add(arucoContext.detector.datGUIOptions.candidates,"minSize").min(0).max(1).onChange(onChange);folder.add(arucoContext.detector.datGUIOptions.candidates,"epsilon").min(0).onChange(onChange);folder.add(arucoContext.detector.datGUIOptions.candidates,"minLength").min(0).step(1).onChange(onChange);var folder=datGui.addFolder("notTooNear");folder.open();folder.add(arucoContext.detector.datGUIOptions.notTooNear,"minDist").min(0).step(1).onChange(onChange);var folder=datGui.addFolder("findMarkers");folder.open();folder.add(arucoContext.detector.datGUIOptions.findMarkers,"warpSize").min(0).step(1).onChange(onChange)};var THREEx=THREEx||{};THREEx.ArucoDebug=function(arucoContext){this.arucoContext=arucoContext;this.canvasElement=document.createElement("canvas");this.canvasElement.width=this.arucoContext.canvas.width;this.canvasElement.height=this.arucoContext.canvas.height};THREEx.ArucoDebug.prototype.setSize=function(width,height){if(this.canvasElement.width!==width)this.canvasElement.width=width;if(this.canvasElement.height!==height)this.canvasElement.height=height};THREEx.ArucoDebug.prototype.clear=function(){var canvas=this.canvasElement;var context=canvas.getContext("2d");context.clearRect(0,0,canvas.width,canvas.height)};THREEx.ArucoDebug.prototype.drawContoursContours=function(){var contours=this.arucoContext.detector.contours;var canvas=this.canvasElement;this.drawContours(contours,0,0,canvas.width,canvas.height,function(hole){return hole?"magenta":"blue"})};THREEx.ArucoDebug.prototype.drawContoursPolys=function(){var contours=this.arucoContext.detector.polys;var canvas=this.canvasElement;this.drawContours(contours,0,0,canvas.width,canvas.height,function(){return"green"})};THREEx.ArucoDebug.prototype.drawContoursCandidates=function(){var contours=this.arucoContext.detector.candidates;var canvas=this.canvasElement;this.drawContours(contours,0,0,canvas.width,canvas.height,function(){return"red"})};THREEx.ArucoDebug.prototype.drawContours=function(contours,x,y,width,height,fn){var i=contours.length,j,contour,point;var canvas=this.canvasElement;var context=canvas.getContext("2d");context.save();while(i--){contour=contours[i];context.strokeStyle=fn(contour.hole);context.beginPath();for(j=0;j<contour.length;++j){point=contour[j];context.moveTo(x+point.x,y+point.y);point=contour[(j+1)%contour.length];context.lineTo(x+point.x,y+point.y)}context.stroke();context.closePath()}context.restore()};THREEx.ArucoDebug.prototype.drawDetectorGrey=function(){var cvImage=arucoContext.detector.grey;this.drawCVImage(cvImage)};THREEx.ArucoDebug.prototype.drawDetectorThreshold=function(){var cvImage=arucoContext.detector.thres;this.drawCVImage(cvImage)};THREEx.ArucoDebug.prototype.drawCVImage=function(cvImage){var detector=this.arucoContext.detector;var canvas=this.canvasElement;var context=canvas.getContext("2d");var imageData=context.createImageData(canvas.width,canvas.height);this.copyCVImage2ImageData(cvImage,imageData);context.putImageData(imageData,0,0)};THREEx.ArucoDebug.prototype.copyCVImage2ImageData=function(cvImage,imageData){var i=cvImage.data.length,j=i*4+3;while(i--){imageData.data[j-=4]=255;imageData.data[j-1]=imageData.data[j-2]=imageData.data[j-3]=cvImage.data[i]}return imageData};THREEx.ArucoDebug.prototype.drawVideo=function(videoElement){var canvas=this.canvasElement;var context=canvas.getContext("2d");context.drawImage(videoElement,0,0,canvas.width,canvas.height)};THREEx.ArucoDebug.prototype.drawMarkerIDs=function(markers){var canvas=this.canvasElement;var context=canvas.getContext("2d");var corners,corner,x,y,i,j;context.save();context.strokeStyle="blue";context.lineWidth=1;for(i=0;i!==markers.length;++i){corners=markers[i].corners;x=Infinity;y=Infinity;for(j=0;j!==corners.length;++j){corner=corners[j];x=Math.min(x,corner.x);y=Math.min(y,corner.y)}context.strokeText(markers[i].id,x,y)}context.restore()};THREEx.ArucoDebug.prototype.drawMarkerCorners=function(markers){var canvas=this.canvasElement;var corners,corner,i,j;var context=canvas.getContext("2d");context.save();context.lineWidth=3;for(i=0;i<markers.length;++i){corners=markers[i].corners;context.strokeStyle="red";context.beginPath();for(j=0;j<corners.length;++j){corner=corners[j];context.moveTo(corner.x,corner.y);corner=corners[(j+1)%corners.length];context.lineTo(corner.x,corner.y)}context.stroke();context.closePath();context.strokeStyle="green";context.strokeRect(corners[0].x-2,corners[0].y-2,4,4)}context.restore()};var THREEx=THREEx||{};THREEx.ArucoMarkerGenerator=function(){};THREEx.ArucoMarkerGenerator.createSVG=function(markerId,svgSize){var domElement=document.createElement("div");domElement.innerHTML=new ArucoMarker(markerId).toSVG(svgSize);return domElement};THREEx.ArucoMarkerGenerator.createImage=function(markerId,width){var canvas=this.createCanvas(markerId,width);var imageURL=canvas.toDataURL();var imageElement=document.createElement("img");imageElement.src=imageURL;return imageElement};THREEx.ArucoMarkerGenerator.createCanvas=function(markerId,width){var canvas=document.createElement("canvas");var context=canvas.getContext("2d");canvas.width=width;canvas.height=width;var arucoMarker=new ArucoMarker(markerId);var marker=arucoMarker.markerMatrix();var margin=canvas.width*.1;var innerW=width-margin*2;var squareW=innerW/7;context.fillStyle="white";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="black";context.fillRect(margin,margin,canvas.width-margin*2,canvas.height-margin*2);for(var y=0;y<5;y++){for(var x=0;x<5;x++){if(marker[x][y]!==1)continue;context.fillStyle="white";context.fillRect(margin+(x+1)*squareW,margin+(y+1)*squareW,squareW+1,squareW+1)}}return canvas};var THREE=THREE||require("three");THREE.WebAR={};THREE.WebAR.MAX_FLOAT32_VALUE=3.4028e38;THREE.WebAR.VRPointCloud=function(vrDisplay){this._vrDisplay=vrDisplay;this._numberOfPointsInLastPointCloud=0;this._bufferGeometry=new THREE.BufferGeometry;this._bufferGeometry.frustumCulled=false;var positions=null;if(vrDisplay){this._pointCloud=new VRPointCloud;vrDisplay.getPointCloud(this._pointCloud,false,0,false);positions=this._pointCloud.points}else{positions=new Float32Array([-1,1,-2,1,1,-2,1,-1,-2,-1,-1,-2])}var colors=new Float32Array(positions.length);var color=new THREE.Color;for(var i=0;i<colors.length;i+=3){if(vrDisplay){positions[i]=THREE.WebAR.MAX_FLOAT32_VALUE;positions[i+1]=THREE.WebAR.MAX_FLOAT32_VALUE;positions[i+2]=THREE.WebAR.MAX_FLOAT32_VALUE}color.setRGB(1,1,1);colors[i]=color.r;colors[i+1]=color.g;colors[i+2]=color.b}this._positions=new THREE.BufferAttribute(positions,3);this._bufferGeometry.addAttribute("position",this._positions);this._colors=new THREE.BufferAttribute(colors,3);this._bufferGeometry.addAttribute("color",this._colors);this._bufferGeometry.computeBoundingSphere();return this};THREE.WebAR.VRPointCloud.prototype.getBufferGeometry=function(){return this._bufferGeometry};THREE.WebAR.VRPointCloud.prototype.update=function(updateBufferGeometry,pointsToSkip,transformPoints){if(!this._vrDisplay)return;this._vrDisplay.getPointCloud(this._pointCloud,!updateBufferGeometry,typeof pointsToSkip==="number"?pointsToSkip:0,!!transformPoints);if(!updateBufferGeometry)return;if(this._pointCloud.numberOfPoints>0){this._positions.needsUpdate=true}};THREE.WebAR.getIndexFromOrientation=function(orientation){var index=0;switch(orientation){case 90:index=1;break;case 180:index=2;break;case 270:index=3;break;default:index=0;break}return index};THREE.WebAR.getIndexFromScreenAndSeeThroughCameraOrientations=function(vrDisplay){var screenOrientation=screen.orientation.angle;var seeThroughCamera=vrDisplay?vrDisplay.getSeeThroughCamera():null;var seeThroughCameraOrientation=seeThroughCamera?seeThroughCamera.orientation:0;var seeThroughCameraOrientationIndex=THREE.WebAR.getIndexFromOrientation(seeThroughCameraOrientation);var screenOrientationIndex=THREE.WebAR.getIndexFromOrientation(screenOrientation);ret=screenOrientationIndex-seeThroughCameraOrientationIndex;if(ret<0){ret+=4}return ret%4};THREE.WebAR.createVRSeeThroughCameraMesh=function(vrDisplay,fallbackVideoPath){var video;var geometry=new THREE.BufferGeometry;if(vrDisplay){var seeThroughCamera=vrDisplay.getSeeThroughCamera();if(!seeThroughCamera)throw"ERROR: Could not get the see through camera!";video=seeThroughCamera;video.readyState=2;video.HAVE_CURRENT_DATA=2;var u=seeThroughCamera.width/seeThroughCamera.textureWidth;var v=seeThroughCamera.height/seeThroughCamera.textureHeight;geometry.WebAR_textureCoords=[new Float32Array([0,0,0,v,u,0,u,v]),new Float32Array([u,0,0,0,u,v,0,v]),new Float32Array([u,v,u,0,0,v,0,0]),new Float32Array([0,v,u,v,0,0,u,0])]}else{var video=document.createElement("video");video.src=typeof fallbackVideoPath==="string"?fallbackVideoPath:"../../resources/videos/sintel.webm";video.play();geometry.WebAR_textureCoords=[new Float32Array([0,0,0,1,1,0,1,1]),new Float32Array([1,0,0,0,1,1,0,1]),new Float32Array([1,1,1,0,0,1,0,0]),new Float32Array([0,1,1,1,0,0,1,0])]}geometry.addAttribute("position",new THREE.BufferAttribute(new Float32Array([-1,1,0,-1,-1,0,1,1,0,1,-1,0]),3));geometry.setIndex(new THREE.BufferAttribute(new Uint16Array([0,1,2,2,1,3]),1));geometry.WebAR_textureCoordIndex=THREE.WebAR.getIndexFromScreenAndSeeThroughCameraOrientations(vrDisplay);var textureCoords=geometry.WebAR_textureCoords[geometry.WebAR_textureCoordIndex];geometry.addAttribute("uv",new THREE.BufferAttribute(new Float32Array(textureCoords),2));geometry.computeBoundingSphere();var videoTexture=new THREE.VideoTexture(video);videoTexture.minFilter=THREE.NearestFilter;videoTexture.magFilter=THREE.NearestFilter;videoTexture.format=THREE.RGBFormat;videoTexture.flipY=false;var material;if(vrDisplay){var vertexShaderSource=["attribute vec3 position;","attribute vec2 uv;","","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","","varying vec2 vUV;","","void main(void) {"," gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);"," vUV = uv;","}"];var fragmentShaderSource=["#extension GL_OES_EGL_image_external : require","precision mediump float;","","varying vec2 vUV;","","uniform samplerExternalOES map;","","void main(void) {"," gl_FragColor = texture2D(map, vUV);","}"];material=new THREE.RawShaderMaterial({uniforms:{map:{type:"t",value:videoTexture}},vertexShader:vertexShaderSource.join("\r\n"),fragmentShader:fragmentShaderSource.join("\r\n"),side:THREE.DoubleSide})}else{material=new THREE.MeshBasicMaterial({color:16777215,side:THREE.DoubleSide,map:videoTexture})}var mesh=new THREE.Mesh(geometry,material);return mesh};THREE.WebAR.updateCameraMeshOrientation=function(vrDisplay,cameraMesh){var textureCoordIndex=THREE.WebAR.getIndexFromScreenAndSeeThroughCameraOrientations(vrDisplay);if(textureCoordIndex!=cameraMesh.geometry.WebAR_textureCoordIndex){var uvs=cameraMesh.geometry.getAttribute("uv");var textureCoords=cameraMesh.geometry.WebAR_textureCoords[textureCoordIndex];cameraMesh.geometry.WebAR_textureCoordIndex=textureCoordIndex;for(var i=0;i<uvs.length;i++){uvs.array[i]=textureCoords[i]}uvs.needsUpdate=true}};THREE.WebAR.createVRSeeThroughCamera=function(vrDisplay,near,far){var camera=new THREE.PerspectiveCamera(60,window.innerWidth/window.innerHeight,near,far);if(vrDisplay){THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay,camera)}return camera};THREE.WebAR.resizeVRSeeThroughCamera=function(vrDisplay,camera){camera.aspect=window.innerWidth/window.innerHeight;if(vrDisplay){var windowWidthBiggerThanHeight=window.innerWidth>window.innerHeight;var seeThroughCamera=vrDisplay.getSeeThroughCamera();if(seeThroughCamera){var cameraWidthBiggerThanHeight=seeThroughCamera.width>seeThroughCamera.height;var swapWidthAndHeight=!(windowWidthBiggerThanHeight&&cameraWidthBiggerThanHeight);var width=swapWidthAndHeight?seeThroughCamera.height:seeThroughCamera.width;var height=swapWidthAndHeight?seeThroughCamera.width:seeThroughCamera.height;var fx=swapWidthAndHeight?seeThroughCamera.focalLengthY:seeThroughCamera.focalLengthX;var fy=swapWidthAndHeight?seeThroughCamera.focalLengthX:seeThroughCamera.focalLengthY;var cx=swapWidthAndHeight?seeThroughCamera.pointY:seeThroughCamera.pointX;var cy=swapWidthAndHeight?seeThroughCamera.pointX:seeThroughCamera.pointY;var xscale=camera.near/fx;var yscale=camera.near/fy;var xoffset=(cx-width/2)*xscale;var yoffset=-(cy-height/2)*yscale;var left=xscale*-width/2-xoffset;var right=xscale*width/2-xoffset;var bottom=yscale*-height/2-yoffset;var top=yscale*height/2-yoffset;camera.projectionMatrix.makePerspective(left,right,top,bottom,camera.near,camera.far);camera.fov=THREE.Math.radToDeg(Math.atan(top*camera.zoom/camera.near))*2}}else{camera.updateProjectionMatrix()}};THREE.WebAR._worldUp=new THREE.Vector3(0,1,0);THREE.WebAR._normalY=new THREE.Vector3;THREE.WebAR._normalZ=new THREE.Vector3;THREE.WebAR._rotationMatrix=new THREE.Matrix4;THREE.WebAR._planeNormal=new THREE.Vector3;THREE.WebAR.rotateObject3D=function(normal1,normal2,object3d){if(normal1 instanceof THREE.Vector3||normal1 instanceof THREE.Vector4){THREE.WebAR._planeNormal.set(normal1.x,normal1.y,normal1.z)}else if(normal1 instanceof Float32Array){THREE.WebAR._planeNormal.set(normal1[0],normal1[1],normal1[2])}else{throw"Unknown normal1 type."}if(normal2 instanceof THREE.Vector3||normal2 instanceof THREE.Vector4){THREE.WebAR._normalZ.set(normal2.x,normal2.y,normal2.z)}else if(normal1 instanceof Float32Array){THREE.WebAR._normalZ.set(normal2[0],normal2[1],normal2[2])}else{throw"Unknown normal2 type."}THREE.WebAR._normalY.crossVectors(THREE.WebAR._planeNormal,THREE.WebAR._normalZ).normalize();THREE.WebAR._rotationMatrix.elements[0]=THREE.WebAR._planeNormal.x;THREE.WebAR._rotationMatrix.elements[1]=THREE.WebAR._planeNormal.y;THREE.WebAR._rotationMatrix.elements[2]=THREE.WebAR._planeNormal.z;THREE.WebAR._rotationMatrix.elements[4]=THREE.WebAR._normalZ.x;THREE.WebAR._rotationMatrix.elements[5]=THREE.WebAR._normalZ.y;THREE.WebAR._rotationMatrix.elements[6]=THREE.WebAR._normalZ.z;THREE.WebAR._rotationMatrix.elements[8]=THREE.WebAR._normalY.x;THREE.WebAR._rotationMatrix.elements[9]=THREE.WebAR._normalY.y;THREE.WebAR._rotationMatrix.elements[10]=THREE.WebAR._normalY.z;object3d.quaternion.setFromRotationMatrix(THREE.WebAR._rotationMatrix)};THREE.WebAR.rotateObject3DWithPickingPlane=function(plane,object3d){if(plane instanceof THREE.Vector3||plane instanceof THREE.Vector4){THREE.WebAR._planeNormal.set(plane.x,plane.y,plane.z)}else if(plane instanceof Float32Array){THREE.WebAR._planeNormal.set(plane[0],plane[1],plane[2])}else{throw"Unknown plane type."}THREE.WebAR._normalY.set(0,1,0);var threshold=.5;if(Math.abs(THREE.WebAR._planeNormal.dot(THREE.WebAR._worldUp))>threshold){THREE.WebAR._normalY.set(0,0,1)}THREE.WebAR._normalZ.crossVectors(THREE.WebAR._planeNormal,THREE.WebAR._normalY).normalize();THREE.WebAR._normalY.crossVectors(THREE.WebAR._normalZ,THREE.WebAR._planeNormal).normalize();THREE.WebAR._rotationMatrix.elements[0]=THREE.WebAR._planeNormal.x;THREE.WebAR._rotationMatrix.elements[1]=THREE.WebAR._planeNormal.y;THREE.WebAR._rotationMatrix.elements[2]=THREE.WebAR._planeNormal.z;THREE.WebAR._rotationMatrix.elements[4]=THREE.WebAR._normalY.x;THREE.WebAR._rotationMatrix.elements[5]=THREE.WebAR._normalY.y;THREE.WebAR._rotationMatrix.elements[6]=THREE.WebAR._normalY.z;THREE.WebAR._rotationMatrix.elements[8]=THREE.WebAR._normalZ.x;THREE.WebAR._rotationMatrix.elements[9]=THREE.WebAR._normalZ.y;THREE.WebAR._rotationMatrix.elements[10]=THREE.WebAR._normalZ.z;object3d.quaternion.setFromRotationMatrix(THREE.WebAR._rotationMatrix)};THREE.WebAR.positionObject3DWithPickingPoint=function(point,object3d){if(point instanceof THREE.Vector3||point instanceof THREE.Vector4){object3d.position.set(point.x,point.y,point.z)}else if(point instanceof Float32Array){object3d.position.set(point[0],point[1],point[2])}else{throw"Unknown point type."}};THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud=function(pointAndPlane,object3d,scale){THREE.WebAR.rotateObject3DWithPickingPlane(pointAndPlane.plane,object3d);THREE.WebAR.positionObject3DWithPickingPoint(pointAndPlane.point,object3d);object3d.position.add(THREE.WebAR._planeNormal.multiplyScalar(scale))};THREE.WebAR.positionAndRotateObject3D=function(position,normal1,normal2,object3d,scale){THREE.WebAR.rotateObject3D(normal1,normal2,object3d);THREE.WebAR.positionObject3DWithPickingPoint(position,object3d);object3d.position.add(THREE.WebAR._planeNormal.multiplyScalar(scale))};(function(root,factory){if(typeof define==="function"&&define.amd){define(["WebAR"],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.WebAR=factory()}})(this,function(){return THREE.WebAR});(function(h){function g(a,b,c,d,e){this._listener=b;this._isOnce=c;this.context=d;this._signal=a;this._priority=e||0}function f(a,b){if(typeof a!=="function")throw Error("listener is a required param of {fn}() and should be a Function.".replace("{fn}",b))}var e={VERSION:"0.7.4"};g.prototype={active:!0,params:null,execute:function(a){var b;this.active&&this._listener&&(a=this.params?this.params.concat(a):a,b=this._listener.apply(this.context,a),this._isOnce&&this.detach());return b},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},getListener:function(){return this._listener},_destroy:function(){delete this._signal;delete this._listener;delete this.context},isOnce:function(){return this._isOnce},toString:function(){return"[SignalBinding isOnce:"+this._isOnce+", isBound:"+this.isBound()+", active:"+this.active+"]"}};e.Signal=function(){this._bindings=[];this._prevParams=null};e.Signal.prototype={memorize:!1,_shouldPropagate:!0,active:!0,_registerListener:function(a,b,c,d){var e=this._indexOfListener(a,c);if(e!==-1){if(a=this._bindings[e],a.isOnce()!==b)throw Error("You cannot add"+(b?"":"Once")+"() then add"+(!b?"":"Once")+"() the same listener without removing the relationship first.")}else a=new g(this,a,b,c,d),this._addBinding(a);this.memorize&&this._prevParams&&a.execute(this._prevParams);return a},_addBinding:function(a){var b=this._bindings.length;do--b;while(this._bindings[b]&&a._priority<=this._bindings[b]._priority);this._bindings.splice(b+1,0,a)},_indexOfListener:function(a,b){for(var c=this._bindings.length,d;c--;)if(d=this._bindings[c],d._listener===a&&d.context===b)return c;return-1},has:function(a,b){return this._indexOfListener(a,b)!==-1},add:function(a,b,c){f(a,"add");return this._registerListener(a,!1,b,c)},addOnce:function(a,b,c){f(a,"addOnce");return this._registerListener(a,!0,b,c)},remove:function(a,b){f(a,"remove");var c=this._indexOfListener(a,b);c!==-1&&(this._bindings[c]._destroy(),this._bindings.splice(c,1));return a},removeAll:function(){for(var a=this._bindings.length;a--;)this._bindings[a]._destroy();this._bindings.length=0},getNumListeners:function(){return this._bindings.length},halt:function(){this._shouldPropagate=!1},dispatch:function(a){if(this.active){var b=Array.prototype.slice.call(arguments),c=this._bindings.length,d;if(this.memorize)this._prevParams=b;if(c){d=this._bindings.slice();this._shouldPropagate=!0;do c--;while(d[c]&&this._shouldPropagate&&d[c].execute(b)!==!1)}}},forget:function(){this._prevParams=null},dispose:function(){this.removeAll();delete this._bindings;delete this._prevParams},toString:function(){return"[Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}};typeof define==="function"&&define.amd?define(e):typeof module!=="undefined"&&module.exports?module.exports=e:h.signals=e})(this);var THREEx=THREEx||{};THREEx.ArBaseControls=function(object3d){this.id=THREEx.ArBaseControls.id++;this.object3d=object3d;this.object3d.matrixAutoUpdate=false;this.object3d.visible=false};THREEx.ArBaseControls.id=0;Object.assign(THREEx.ArBaseControls.prototype,THREE.EventDispatcher.prototype);THREEx.ArBaseControls.prototype.update=function(){console.assert(false,"you need to implement your own update")};THREEx.ArBaseControls.prototype.name=function(){console.assert(false,"you need to implement your own .name()");return"Not yet implemented - name()"};var THREEx=THREEx||{};THREEx.ARClickability=function(sourceElement){this._sourceElement=sourceElement;var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);this._cameraPicking=new THREE.PerspectiveCamera(42,fullWidth/fullHeight,.1,100);console.warn("THREEx.ARClickability works only in modelViewMatrix");console.warn("OBSOLETE OBSOLETE! instead use THREEx.HitTestingPlane or THREEx.HitTestingTango")};THREEx.ARClickability.prototype.onResize=function(){var sourceElement=this._sourceElement;var cameraPicking=this._cameraPicking;var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);cameraPicking.aspect=fullWidth/fullHeight;cameraPicking.updateProjectionMatrix()};THREEx.ARClickability.prototype.computeIntersects=function(domEvent,objects){var sourceElement=this._sourceElement;var cameraPicking=this._cameraPicking;var eventCoords=new THREE.Vector3;eventCoords.x=domEvent.layerX/parseInt(sourceElement.style.width)*2-1;eventCoords.y=-(domEvent.layerY/parseInt(sourceElement.style.height))*2+1;var raycaster=new THREE.Raycaster;raycaster.setFromCamera(eventCoords,cameraPicking);var intersects=raycaster.intersectObjects(objects);return intersects};THREEx.ARClickability.prototype.update=function(){};THREEx.ARClickability.tangoPickingPointCloud=function(artoolkitContext,mouseX,mouseY){var vrDisplay=artoolkitContext._tangoContext.vrDisplay;if(vrDisplay===null)return null;var pointAndPlane=vrDisplay.getPickingPointAndPlaneInPointCloud(mouseX,mouseY);if(pointAndPlane==null){console.warn("Could not retrieve the correct point and plane.");return null}var boundingSphereRadius=.01;var object3d=new THREE.Object3D;THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud(pointAndPlane,object3d,boundingSphereRadius);object3d.rotateZ(-Math.PI/2);var result={};result.position=object3d.position;result.quaternion=object3d.quaternion;return result};var THREEx=THREEx||{};THREEx.ArMarkerCloak=function(videoTexture){var updateInShaderEnabled=true;var geometry=new THREE.PlaneGeometry(1.3+.25,1.85+.25,1,8).translate(0,-.3,0);var material=new THREE.ShaderMaterial({vertexShader:THREEx.ArMarkerCloak.vertexShader,fragmentShader:THREEx.ArMarkerCloak.fragmentShader,transparent:true,uniforms:{texture:{value:videoTexture},opacity:{value:.5}},defines:{updateInShaderEnabled:updateInShaderEnabled?1:0}});var cloakMesh=new THREE.Mesh(geometry,material);cloakMesh.rotation.x=-Math.PI/2;this.object3d=cloakMesh;var xMin=-.65;var xMax=.65;var yMin=.65+.1;var yMax=.95+.1;var originalsFaceVertexUvs=[[]];for(var faceIndex=0;faceIndex<cloakMesh.geometry.faces.length;faceIndex++){originalsFaceVertexUvs[0][faceIndex]=[];originalsFaceVertexUvs[0][faceIndex][0]=new THREE.Vector2;originalsFaceVertexUvs[0][faceIndex][1]=new THREE.Vector2;originalsFaceVertexUvs[0][faceIndex][2]=new THREE.Vector2}for(var i=0;i<cloakMesh.geometry.parameters.heightSegments/2;i++){originalsFaceVertexUvs[0][i*4+0][0].set(xMin/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+0][1].set(xMin/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+0][2].set(xMax/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+1][0].set(xMin/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+1][1].set(xMax/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+1][2].set(xMax/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+2][0].set(xMin/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+2][1].set(xMin/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+2][2].set(xMax/2+.5,yMin/2+.5);originalsFaceVertexUvs[0][i*4+3][0].set(xMin/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+3][1].set(xMax/2+.5,yMax/2+.5);originalsFaceVertexUvs[0][i*4+3][2].set(xMax/2+.5,yMin/2+.5)}if(updateInShaderEnabled===true){cloakMesh.geometry.faceVertexUvs=originalsFaceVertexUvs;cloakMesh.geometry.uvsNeedUpdate=true}var originalOrthoVertices=[];originalOrthoVertices.push(new THREE.Vector3(xMin,yMax,0));originalOrthoVertices.push(new THREE.Vector3(xMax,yMax,0));originalOrthoVertices.push(new THREE.Vector3(xMin,yMin,0));originalOrthoVertices.push(new THREE.Vector3(xMax,yMin,0));var material=new THREE.MeshNormalMaterial({transparent:true,opacity:.5,side:THREE.DoubleSide});var geometry=new THREE.PlaneGeometry(1,1);var orthoMesh=new THREE.Mesh(geometry,material);this.orthoMesh=orthoMesh;this.update=function(modelViewMatrix,cameraProjectionMatrix){updateOrtho(modelViewMatrix,cameraProjectionMatrix);if(updateInShaderEnabled===false){updateUvs(modelViewMatrix,cameraProjectionMatrix)}};return;function updateUvs(modelViewMatrix,cameraProjectionMatrix){var transformedUv=new THREE.Vector3;originalsFaceVertexUvs[0].forEach(function(faceVertexUvs,faceIndex){faceVertexUvs.forEach(function(originalUv,uvIndex){transformedUv.x=originalUv.x*2-1;transformedUv.y=originalUv.y*2-1;transformedUv.z=0;transformedUv.applyMatrix4(modelViewMatrix);transformedUv.applyMatrix4(cameraProjectionMatrix);transformedUv.x/=transformedUv.z;transformedUv.y/=transformedUv.z;transformedUv.x=transformedUv.x/2+.5;transformedUv.y=transformedUv.y/2+.5;cloakMesh.geometry.faceVertexUvs[0][faceIndex][uvIndex].set(transformedUv.x,transformedUv.y)})});cloakMesh.geometry.uvsNeedUpdate=true}function updateOrtho(modelViewMatrix,cameraProjectionMatrix){var transformedUvs=[];originalOrthoVertices.forEach(function(originalOrthoVertices,index){var transformedUv=originalOrthoVertices.clone();transformedUv.applyMatrix4(modelViewMatrix);transformedUv.applyMatrix4(cameraProjectionMatrix);transformedUv.x/=transformedUv.z;transformedUv.y/=transformedUv.z;transformedUvs.push(transformedUv)});for(var i=0;i<transformedUvs.length;i++){orthoMesh.geometry.vertices[i].copy(transformedUvs[i])}orthoMesh.geometry.computeBoundingSphere();orthoMesh.geometry.verticesNeedUpdate=true}};THREEx.ArMarkerCloak.markerSpaceShaderFunction="\n"+" vec2 transformUvToMarkerSpace(vec2 originalUv){\n"+" vec3 transformedUv;\n"+" // set transformedUv - from UV coord to clip coord\n"+" transformedUv.x = originalUv.x * 2.0 - 1.0;\n"+" transformedUv.y = originalUv.y * 2.0 - 1.0;\n"+" transformedUv.z = 0.0;\n"+"\n"+" // apply modelViewMatrix and projectionMatrix\n"+" transformedUv = (projectionMatrix * modelViewMatrix * vec4( transformedUv, 1.0 ) ).xyz;\n"+"\n"+" // apply perspective\n"+" transformedUv.x /= transformedUv.z;\n"+" transformedUv.y /= transformedUv.z;\n"+"\n"+" // set back from clip coord to Uv coord\n"+" transformedUv.x = transformedUv.x / 2.0 + 0.5;\n"+" transformedUv.y = transformedUv.y / 2.0 + 0.5;\n"+"\n"+" // return the result\n"+" return transformedUv.xy;\n"+" }";THREEx.ArMarkerCloak.vertexShader=THREEx.ArMarkerCloak.markerSpaceShaderFunction+" varying vec2 vUv;\n"+"\n"+" void main(){\n"+" // pass the UV to the fragment\n"+" #if (updateInShaderEnabled == 1)\n"+" vUv = transformUvToMarkerSpace(uv);\n"+" #else\n"+" vUv = uv;\n"+" #endif\n"+"\n"+" // compute gl_Position\n"+" vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n"+" gl_Position = projectionMatrix * mvPosition;\n"+" }";
THREEx.ArMarkerCloak.fragmentShader="\n"+" varying vec2 vUv;\n"+" uniform sampler2D texture;\n"+" uniform float opacity;\n"+"\n"+" void main(void){\n"+" vec3 color = texture2D( texture, vUv ).rgb;\n"+"\n"+" gl_FragColor = vec4( color, opacity);\n"+" }";var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkerControls=THREEx.ArMarkerControls=function(context,object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.context=context;this.parameters={size:1,type:"unknown",patternUrl:null,barcodeValue:null,changeMatrixMode:"modelViewMatrix",minConfidence:.6};var possibleValues=["pattern","barcode","unknown"];console.assert(possibleValues.indexOf(this.parameters.type)!==-1,"illegal value",this.parameters.type);var possibleValues=["modelViewMatrix","cameraTransformMatrix"];console.assert(possibleValues.indexOf(this.parameters.changeMatrixMode)!==-1,"illegal value",this.parameters.changeMatrixMode);this.object3d=object3d;this.object3d.matrixAutoUpdate=false;this.object3d.visible=false;setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}context.addMarker(this);if(_this.context.parameters.trackingBackend==="artoolkit"){this._initArtoolkit()}else if(_this.context.parameters.trackingBackend==="aruco"){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)}else if(_this.context.parameters.trackingBackend==="tango"){this._initTango()}else console.assert(false)};ARjs.MarkerControls.prototype=Object.create(THREEx.ArBaseControls.prototype);ARjs.MarkerControls.prototype.constructor=THREEx.ArMarkerControls;ARjs.MarkerControls.prototype.dispose=function(){this.context.removeMarker(this)};ARjs.MarkerControls.prototype.updateWithModelViewMatrix=function(modelViewMatrix){var markerObject3D=this.object3d;markerObject3D.visible=true;if(this.context.parameters.trackingBackend==="artoolkit"){var tmpMatrix=(new THREE.Matrix4).copy(this.context._artoolkitProjectionAxisTransformMatrix);tmpMatrix.multiply(modelViewMatrix);modelViewMatrix.copy(tmpMatrix)}else if(this.context.parameters.trackingBackend==="aruco"){}else if(this.context.parameters.trackingBackend==="tango"){}else console.assert(false);if(this.context.parameters.trackingBackend!=="tango"){var markerAxisTransformMatrix=(new THREE.Matrix4).makeRotationX(Math.PI/2);modelViewMatrix.multiply(markerAxisTransformMatrix)}if(this.parameters.changeMatrixMode==="modelViewMatrix"){markerObject3D.matrix.copy(modelViewMatrix)}else if(this.parameters.changeMatrixMode==="cameraTransformMatrix"){markerObject3D.matrix.getInverse(modelViewMatrix)}else{console.assert(false)}markerObject3D.matrix.decompose(markerObject3D.position,markerObject3D.quaternion,markerObject3D.scale);this.dispatchEvent({type:"markerFound"})};ARjs.MarkerControls.prototype.name=function(){var name="";name+=this.parameters.type;if(this.parameters.type==="pattern"){var url=this.parameters.patternUrl;var basename=url.replace(/^.*\//g,"");name+=" - "+basename}else if(this.parameters.type==="barcode"){name+=" - "+this.parameters.barcodeValue}else{console.assert(false,"no .name() implemented for this marker controls")}return name};ARjs.MarkerControls.prototype._initArtoolkit=function(){var _this=this;var artoolkitMarkerId=null;var delayedInitTimerId=setInterval(function(){var arController=_this.context.arController;if(arController===null)return;clearInterval(delayedInitTimerId);delayedInitTimerId=null;postInit()},1e3/50);return;function postInit(){var arController=_this.context.arController;console.assert(arController!==null);if(_this.parameters.type==="pattern"){arController.loadMarker(_this.parameters.patternUrl,function(markerId){artoolkitMarkerId=markerId;arController.trackPatternMarkerId(artoolkitMarkerId,_this.parameters.size)})}else if(_this.parameters.type==="barcode"){artoolkitMarkerId=_this.parameters.barcodeValue;arController.trackBarcodeMarkerId(artoolkitMarkerId,_this.parameters.size)}else if(_this.parameters.type==="unknown"){artoolkitMarkerId=null}else{console.log(false,"invalid marker type",_this.parameters.type)}arController.addEventListener("getMarker",function(event){if(event.data.type===artoolkit.PATTERN_MARKER&&_this.parameters.type==="pattern"){if(artoolkitMarkerId===null)return;if(event.data.marker.idPatt===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.BARCODE_MARKER&&_this.parameters.type==="barcode"){if(artoolkitMarkerId===null)return;if(event.data.marker.idMatrix===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.UNKNOWN_MARKER&&_this.parameters.type==="unknown"){onMarkerFound(event)}})}function onMarkerFound(event){if(event.data.type===artoolkit.PATTERN_MARKER&&event.data.marker.cfPatt<_this.parameters.minConfidence)return;if(event.data.type===artoolkit.BARCODE_MARKER&&event.data.marker.cfMatt<_this.parameters.minConfidence)return;var modelViewMatrix=(new THREE.Matrix4).fromArray(event.data.matrix);_this.updateWithModelViewMatrix(modelViewMatrix)}};ARjs.MarkerControls.prototype._initAruco=function(){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)};ARjs.MarkerControls.prototype._initTango=function(){var _this=this;console.log("init tango ArMarkerControls")};var THREEx=THREEx||{};THREEx.ArMarkerHelper=function(markerControls){this.object3d=new THREE.Group;var mesh=new THREE.AxisHelper;this.object3d.add(mesh);var text=markerControls.id;var canvas=document.createElement("canvas");canvas.width=64;canvas.height=64;var context=canvas.getContext("2d");var texture=new THREE.CanvasTexture(canvas);context.font="48px monospace";context.fillStyle="rgba(192,192,255, 0.5)";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="darkblue";context.fillText(text,canvas.width/4,3*canvas.height/4);texture.needsUpdate=true;var geometry=new THREE.PlaneGeometry(1,1);var material=new THREE.MeshBasicMaterial({map:texture,transparent:true});var mesh=new THREE.Mesh(geometry,material);mesh.rotation.x=-Math.PI/2;this.object3d.add(mesh)};var THREEx=THREEx||{};THREEx.ArSmoothedControls=function(object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.object3d.visible=false;this._lastLerpStepAt=null;this._visibleStartedAt=null;this._unvisibleStartedAt=null;parameters=parameters||{};this.parameters={lerpPosition:.8,lerpQuaternion:.2,lerpScale:.7,lerpStepDelay:1/60,minVisibleDelay:0,minUnvisibleDelay:.2};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};THREEx.ArSmoothedControls.prototype=Object.create(THREEx.ArBaseControls.prototype);THREEx.ArSmoothedControls.prototype.constructor=THREEx.ArSmoothedControls;THREEx.ArSmoothedControls.prototype.update=function(targetObject3d){var object3d=this.object3d;var parameters=this.parameters;var wasVisible=object3d.visible;var present=performance.now()/1e3;if(targetObject3d.visible===false)this._visibleStartedAt=null;if(targetObject3d.visible===true)this._unvisibleStartedAt=null;if(targetObject3d.visible===true&&this._visibleStartedAt===null)this._visibleStartedAt=present;if(targetObject3d.visible===false&&this._unvisibleStartedAt===null)this._unvisibleStartedAt=present;if(wasVisible===false&&targetObject3d.visible===true){var visibleFor=present-this._visibleStartedAt;if(visibleFor>=this.parameters.minVisibleDelay){object3d.visible=true;snapDirectlyToTarget()}}if(wasVisible===true&&targetObject3d.visible===false){var unvisibleFor=present-this._unvisibleStartedAt;if(unvisibleFor>=this.parameters.minUnvisibleDelay){object3d.visible=false}}if(this._lastLerpStepAt===null){applyOneSlerpStep();this._lastLerpStepAt=present}else{var nStepsToDo=Math.floor((present-this._lastLerpStepAt)/this.parameters.lerpStepDelay);for(var i=0;i<nStepsToDo;i++){applyOneSlerpStep();this._lastLerpStepAt+=this.parameters.lerpStepDelay}}if(false){snapDirectlyToTarget()}this.object3d.updateMatrix();if(wasVisible===false&&object3d.visible===true){this.dispatchEvent({type:"becameVisible"})}if(wasVisible===true&&object3d.visible===false){this.dispatchEvent({type:"becameUnVisible"})}return;function snapDirectlyToTarget(){object3d.position.copy(targetObject3d.position);object3d.quaternion.copy(targetObject3d.quaternion);object3d.scale.copy(targetObject3d.scale)}function applyOneSlerpStep(){object3d.position.lerp(targetObject3d.position,parameters.lerpPosition);object3d.quaternion.slerp(targetObject3d.quaternion,parameters.lerpQuaternion);object3d.scale.lerp(targetObject3d.scale,parameters.lerpScale)}};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Context=THREEx.ArToolkitContext=function(parameters){var _this=this;_this._updatedAt=null;this.parameters={trackingBackend:"artoolkit",debug:false,detectionMode:"mono",matrixCodeType:"3x3",cameraParametersUrl:ARjs.Context.baseURL+"parameters/camera_para.dat",maxDetectionRate:60,canvasWidth:640,canvasHeight:480,patternRatio:.5,imageSmoothingEnabled:false};console.assert(["artoolkit","aruco","tango"].indexOf(this.parameters.trackingBackend)!==-1,"invalid parameter trackingBackend",this.parameters.trackingBackend);console.assert(["color","color_and_matrix","mono","mono_and_matrix"].indexOf(this.parameters.detectionMode)!==-1,"invalid parameter detectionMode",this.parameters.detectionMode);this.arController=null;this.arucoContext=null;_this.initialized=false;this._arMarkersControls=[];setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};Object.assign(ARjs.Context.prototype,THREE.EventDispatcher.prototype);ARjs.Context.baseURL="https://jeromeetienne.github.io/AR.js/three.js/";ARjs.Context.REVISION="1.6.
1
";ARjs.Context.createDefaultCamera=function(trackingBackend){console.assert(false,"use ARjs.Utils.createDefaultCamera instead");if(trackingBackend==="artoolkit"){var camera=new THREE.Camera}else if(trackingBackend==="aruco"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else if(trackingBackend==="tango"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else console.assert(false);return camera};ARjs.Context.prototype.init=function(onCompleted){var _this=this;if(this.parameters.trackingBackend==="artoolkit"){this._initArtoolkit(done)}else if(this.parameters.trackingBackend==="aruco"){this._initAruco(done)}else if(this.parameters.trackingBackend==="tango"){this._initTango(done)}else console.assert(false);return;function done(){_this.dispatchEvent({type:"initialized"});_this.initialized=true;onCompleted&&onCompleted()}};ARjs.Context.prototype.update=function(srcElement){if(this.parameters.trackingBackend==="artoolkit"&&this.arController===null)return false;var present=performance.now();if(this._updatedAt!==null&&present-this._updatedAt<1e3/this.parameters.maxDetectionRate){return false}this._updatedAt=present;this._arMarkersControls.forEach(function(markerControls){markerControls.object3d.visible=false});if(this.parameters.trackingBackend==="artoolkit"){this._updateArtoolkit(srcElement)}else if(this.parameters.trackingBackend==="aruco"){this._updateAruco(srcElement)}else if(this.parameters.trackingBackend==="tango"){this._updateTango(srcElement)}else{console.assert(false)}this.dispatchEvent({type:"sourceProcessed"});return true};ARjs.Context.prototype.addMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);this._arMarkersControls.push(arMarkerControls)};ARjs.Context.prototype.removeMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);var index=this.arMarkerControlss.indexOf(artoolkitMarker);console.assert(index!==index);this._arMarkersControls.splice(index,1)};ARjs.Context.prototype._initArtoolkit=function(onCompleted){var _this=this;this._artoolkitProjectionAxisTransformMatrix=new THREE.Matrix4;this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationY(Math.PI));this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationZ(Math.PI));var cameraParameters=new ARCameraParam(_this.parameters.cameraParametersUrl,function(){var arController=new ARController(_this.parameters.canvasWidth,_this.parameters.canvasHeight,cameraParameters);_this.arController=arController;arController.ctx.mozImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.webkitImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.msImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.imageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;if(_this.parameters.debug===true){arController.debugSetup();arController.canvas.style.position="absolute";arController.canvas.style.top="0px";arController.canvas.style.opacity="0.6";arController.canvas.style.pointerEvents="none";arController.canvas.style.zIndex="-1"}var detectionModes={color:artoolkit.AR_TEMPLATE_MATCHING_COLOR,color_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX,mono:artoolkit.AR_TEMPLATE_MATCHING_MONO,mono_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_MONO_AND_MATRIX};var detectionMode=detectionModes[_this.parameters.detectionMode];console.assert(detectionMode!==undefined);arController.setPatternDetectionMode(detectionMode);var matrixCodeTypes={"3x3":artoolkit.AR_MATRIX_CODE_3x3,"3x3_HAMMING63":artoolkit.AR_MATRIX_CODE_3x3_HAMMING63,"3x3_PARITY65":artoolkit.AR_MATRIX_CODE_3x3_PARITY65,"4x4":artoolkit.AR_MATRIX_CODE_4x4,"4x4_BCH_13_9_3":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_9_3,"4x4_BCH_13_5_5":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_5_5};var matrixCodeType=matrixCodeTypes[_this.parameters.matrixCodeType];console.assert(matrixCodeType!==undefined);arController.setMatrixCodeType(matrixCodeType);arController.setPattRatio(_this.parameters.patternRatio);onCompleted()});return this};ARjs.Context.prototype.getProjectionMatrix=function(srcElement){console.assert(this.parameters.trackingBackend==="artoolkit");console.assert(this.arController,"arController MUST be initialized to call this function");var projectionMatrixArr=this.arController.getCameraMatrix();var projectionMatrix=(new THREE.Matrix4).fromArray(projectionMatrixArr);projectionMatrix.multiply(this._artoolkitProjectionAxisTransformMatrix);return projectionMatrix};ARjs.Context.prototype._updateArtoolkit=function(srcElement){this.arController.process(srcElement)};ARjs.Context.prototype._initAruco=function(onCompleted){this.arucoContext=new THREEx.ArucoContext;this.arucoContext.canvas.width=this.parameters.canvasWidth;this.arucoContext.canvas.height=this.parameters.canvasHeight;var context=this.arucoContext.canvas.getContext("2d");context.webkitImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.msImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.imageSmoothingEnabled=this.parameters.imageSmoothingEnabled;setTimeout(function(){onCompleted()},0)};ARjs.Context.prototype._updateAruco=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var detectedMarkers=this.arucoContext.detect(srcElement);detectedMarkers.forEach(function(detectedMarker){var foundControls=null;for(var i=0;i<arMarkersControls.length;i++){console.assert(arMarkersControls[i].parameters.type==="barcode");if(arMarkersControls[i].parameters.barcodeValue===detectedMarker.id){foundControls=arMarkersControls[i];break}}if(foundControls===null)return;var tmpObject3d=new THREE.Object3D;_this.arucoContext.updateObject3D(tmpObject3d,foundControls._arucoPosit,foundControls.parameters.size,detectedMarker);tmpObject3d.updateMatrix();foundControls.updateWithModelViewMatrix(tmpObject3d.matrix)})};ARjs.Context.prototype._initTango=function(onCompleted){var _this=this;if(navigator.getVRDisplays){}else if(navigator.getVRDevices){alert("Your browser supports WebVR but not the latest version. See <a href='http://webvr.info'>webvr.info</a> for more info.")}else{alert("Your browser does not support WebVR. See <a href='http://webvr.info'>webvr.info</a> for assistance.")}this._tangoContext={vrDisplay:null,vrPointCloud:null,frameData:new VRFrameData};navigator.getVRDisplays().then(function(vrDisplays){if(vrDisplays.length===0)alert("no vrDisplays available");var vrDisplay=_this._tangoContext.vrDisplay=vrDisplays[0];console.log("vrDisplays.displayName :",vrDisplay.displayName);if(vrDisplay.displayName==="Tango VR Device"){_this._tangoContext.vrPointCloud=new THREE.WebAR.VRPointCloud(vrDisplay,true)}onCompleted()})};ARjs.Context.prototype._updateTango=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var tangoContext=this._tangoContext;var vrDisplay=this._tangoContext.vrDisplay;if(vrDisplay===null)return;if(vrDisplay.displayName==="Tango VR Device"){var showPointCloud=true;var pointsToSkip=0;_this._tangoContext.vrPointCloud.update(showPointCloud,pointsToSkip,true)}if(this._arMarkersControls.length===0)return;var foundControls=this._arMarkersControls[0];var frameData=this._tangoContext.frameData;vrDisplay.getFrameData(frameData);if(frameData.pose.position===null)return;if(frameData.pose.orientation===null)return;var position=(new THREE.Vector3).fromArray(frameData.pose.position);var quaternion=(new THREE.Quaternion).fromArray(frameData.pose.orientation);var scale=new THREE.Vector3(1,1,1);var cameraTransformMatrix=(new THREE.Matrix4).compose(position,quaternion,scale);var modelViewMatrix=new THREE.Matrix4;modelViewMatrix.getInverse(cameraTransformMatrix);foundControls.updateWithModelViewMatrix(modelViewMatrix)};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Profile=THREEx.ArToolkitProfile=function(){this.reset();this.performance("default")};ARjs.Profile.prototype._guessPerformanceLabel=function(){var isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/webOS/i)||navigator.userAgent.match(/iPhone/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPod/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Windows Phone/i)?true:false;if(isMobile===true){return"phone-normal"}return"desktop-normal"};ARjs.Profile.prototype.reset=function(){this.sourceParameters={sourceType:"webcam"};this.contextParameters={cameraParametersUrl:THREEx.ArToolkitContext.baseURL+"../data/data/camera_para.dat",detectionMode:"mono"};this.defaultMarkerParameters={type:"pattern",patternUrl:THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro",changeMatrixMode:"modelViewMatrix"};return this};ARjs.Profile.prototype.performance=function(label){if(label==="default"){label=this._guessPerformanceLabel()}if(label==="desktop-fast"){this.contextParameters.canvasWidth=640*3;this.contextParameters.canvasHeight=480*3;this.contextParameters.maxDetectionRate=30}else if(label==="desktop-normal"){this.contextParameters.canvasWidth=640;this.contextParameters.canvasHeight=480;this.contextParameters.maxDetectionRate=60}else if(label==="phone-normal"){this.contextParameters.canvasWidth=80*4;this.contextParameters.canvasHeight=60*4;this.contextParameters.maxDetectionRate=30}else if(label==="phone-slow"){this.contextParameters.canvasWidth=80*3;this.contextParameters.canvasHeight=60*3;this.contextParameters.maxDetectionRate=30}else{console.assert(false,"unknonwn label "+label)}return this};ARjs.Profile.prototype.defaultMarker=function(trackingBackend){trackingBackend=trackingBackend||this.contextParameters.trackingBackend;if(trackingBackend==="artoolkit"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="pattern";this.defaultMarkerParameters.patternUrl=THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro"}else if(trackingBackend==="aruco"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else if(trackingBackend==="tango"){this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else console.assert(false);return this};ARjs.Profile.prototype.sourceWebcam=function(){this.sourceParameters.sourceType="webcam";delete this.sourceParameters.sourceUrl;return this};ARjs.Profile.prototype.sourceVideo=function(url){this.sourceParameters.sourceType="video";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.sourceImage=function(url){this.sourceParameters.sourceType="image";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.trackingBackend=function(trackingBackend){console.warn("stop profile.trackingBackend() obsolete function. use .trackingMethod instead");this.contextParameters.trackingBackend=trackingBackend;return this};ARjs.Profile.prototype.changeMatrixMode=function(changeMatrixMode){this.defaultMarkerParameters.changeMatrixMode=changeMatrixMode;return this};ARjs.Profile.prototype.trackingMethod=function(trackingMethod){var data=ARjs.Utils.parseTrackingMethod(trackingMethod);this.defaultMarkerParameters.markersAreaEnabled=data.markersAreaEnabled;this.contextParameters.trackingBackend=data.trackingBackend;return this};ARjs.Profile.prototype.checkIfValid=function(){if(this.contextParameters.trackingBackend==="tango"){this.sourceImage(THREEx.ArToolkitContext.baseURL+"../data/images/img.jpg")}return this};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Source=THREEx.ArToolkitSource=function(parameters){var _this=this;this.ready=false;this.domElement=null;this.parameters={sourceType:"webcam",sourceUrl:null,deviceId:null,sourceWidth:640,sourceHeight:480,displayWidth:640,displayHeight:480};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};ARjs.Source.prototype.init=function(onReady,onError){var _this=this;if(this.parameters.sourceType==="image"){var domElement=this._initSourceImage(onSourceReady,onError)}else if(this.parameters.sourceType==="video"){var domElement=this._initSourceVideo(onSourceReady,onError)}else if(this.parameters.sourceType==="webcam"){var domElement=this._initSourceWebcam(onSourceReady,onError)}else{console.assert(false)}this.domElement=domElement;this.domElement.style.position="absolute";this.domElement.style.top="0px";this.domElement.style.left="0px";this.domElement.style.zIndex="-2";return this;function onSourceReady(){document.body.appendChild(_this.domElement);_this.ready=true;onReady&&onReady()}};ARjs.Source.prototype._initSourceImage=function(onReady){var domElement=document.createElement("img");domElement.src=this.parameters.sourceUrl;domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.naturalWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceVideo=function(onReady){var domElement=document.createElement("video");domElement.src=this.parameters.sourceUrl;domElement.style.objectFit="initial";domElement.autoplay=true;domElement.webkitPlaysinline=true;domElement.controls=false;domElement.loop=true;domElement.muted=true;document.body.addEventListener("click",function onClick(){document.body.removeEventListener("click",onClick);domElement.play()});domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceWebcam=function(onReady,onError){var _this=this;onError=onError||function(error){alert("Webcam Error\nName: "+error.name+"\nMessage: "+error.message)};var domElement=document.createElement("video");domElement.setAttribute("autoplay","");domElement.setAttribute("muted","");domElement.setAttribute("playsinline","");domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";if(navigator.mediaDevices===undefined||navigator.mediaDevices.enumerateDevices===undefined||navigator.mediaDevices.getUserMedia===undefined){if(navigator.mediaDevices===undefined)var fctName="navigator.mediaDevices";else if(navigator.mediaDevices.enumerateDevices===undefined)var fctName="navigator.mediaDevices.enumerateDevices";else if(navigator.mediaDevices.getUserMedia===undefined)var fctName="navigator.mediaDevices.getUserMedia";else console.assert(false);onError({name:"",message:"WebRTC issue-! "+fctName+" not present in your browser"});return null}navigator.mediaDevices.enumerateDevices().then(function(devices){var userMediaConstraints={audio:false,video:{facingMode:"environment",width:{ideal:_this.parameters.sourceWidth},height:{ideal:_this.parameters.sourceHeight}}};if(null!==_this.parameters.deviceId){userMediaConstraints.video.deviceId={exact:_this.parameters.deviceId}}navigator.mediaDevices.getUserMedia(userMediaConstraints).then(function success(stream){domElement.srcObject=stream;document.body.addEventListener("click",function(){domElement.play()});var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50)}).catch(function(error){onError({name:error.name,message:error.message})})}).catch(function(error){onError({message:error.message})});return domElement};ARjs.Source.prototype.hasMobileTorch=function(){var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false)return false;if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];if(videoTrack.getCapabilities===undefined)return false;var capabilities=videoTrack.getCapabilities();return capabilities.torch?true:false};ARjs.Source.prototype.toggleMobileTorch=function(){console.assert(this.hasMobileTorch()===true);var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false){alert("enabling mobile torch is available only on webcam");return}if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];var capabilities=videoTrack.getCapabilities();if(!capabilities.torch){alert("no mobile torch is available on your camera");return}this._currentTorchStatus=this._currentTorchStatus===false?true:false;videoTrack.applyConstraints({advanced:[{torch:this._currentTorchStatus}]}).catch(function(error){console.log(error)})};ARjs.Source.prototype.domElementWidth=function(){return parseInt(this.domElement.style.width)};ARjs.Source.prototype.domElementHeight=function(){return parseInt(this.domElement.style.height)};ARjs.Source.prototype.onResizeElement=function(){var _this=this;var screenWidth=window.innerWidth;var screenHeight=window.innerHeight;console.assert(arguments.length===0);if(this.domElement.nodeName==="IMG"){var sourceWidth=this.domElement.naturalWidth;var sourceHeight=this.domElement.naturalHeight}else if(this.domElement.nodeName==="VIDEO"){var sourceWidth=this.domElement.videoWidth;var sourceHeight=this.domElement.videoHeight}else{console.assert(false)}var sourceAspect=sourceWidth/sourceHeight;var screenAspect=screenWidth/screenHeight;if(screenAspect<sourceAspect){var newWidth=sourceAspect*screenHeight;this.domElement.style.width=newWidth+"px";this.domElement.style.marginLeft=-(newWidth-screenWidth)/2+"px";this.domElement.style.height=screenHeight+"px";this.domElement.style.marginTop="0px"}else{var newHeight=1/(sourceAspect/screenWidth);this.domElement.style.height=newHeight+"px";this.domElement.style.marginTop=-(newHeight-screenHeight)/2+"px";this.domElement.style.width=screenWidth+"px";this.domElement.style.marginLeft="0px"}};ARjs.Source.prototype.copyElementSizeTo=function(otherElement){if(window.innerWidth>window.innerHeight){otherElement.style.width=this.domElement.style.width;otherElement.style.height=this.domElement.style.height;otherElement.style.marginLeft=this.domElement.style.marginLeft;otherElement.style.marginTop=this.domElement.style.marginTop}else{otherElement.style.height=this.domElement.style.height;otherElement.style.width=parseInt(otherElement.style.height)*4/3+"px";otherElement.style.marginLeft=(window.innerWidth-parseInt(otherElement.style.width))/2+"px";otherElement.style.marginTop=0}};ARjs.Source.prototype.copySizeTo=function(){console.warn("obsolete function arToolkitSource.copySizeTo. Use arToolkitSource.copyElementSizeTo");this.copyElementSizeTo.apply(this,arguments)};ARjs.Source.prototype.onResize=function(arToolkitContext,renderer,camera){if(arguments.length!==3){console.warn("obsolete function arToolkitSource.onResize. Use arToolkitSource.onResizeElement");return this.onResizeElement.apply(this,arguments)}var trackingBackend=arToolkitContext.parameters.trackingBackend;if(trackingBackend==="artoolkit"){this.onResizeElement();var isAframe=renderer.domElement.dataset.aframeCanvas?true:false;if(isAframe===false){this.copyElementSizeTo(renderer.domElement)}else{}if(arToolkitContext.arController!==null){this.copyElementSizeTo(arToolkitContext.arController.canvas)}}else if(trackingBackend==="aruco"){this.onResizeElement();this.copyElementSizeTo(renderer.domElement);this.copyElementSizeTo(arToolkitContext.arucoContext.canvas)}else if(trackingBackend==="tango"){renderer.setSize(window.innerWidth,window.innerHeight)}else console.assert(false,"unhandled trackingBackend "+trackingBackend);if(trackingBackend==="artoolkit"){if(arToolkitContext.arController!==null){camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix())}}else if(trackingBackend==="aruco"){camera.aspect=renderer.domElement.width/renderer.domElement.height;camera.updateProjectionMatrix()}else if(trackingBackend==="tango"){var vrDisplay=arToolkitContext._tangoContext.vrDisplay;if(vrDisplay&&vrDisplay.displayName==="Tango VR Device")THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay,camera)}else console.assert(false,"unhandled trackingBackend "+trackingBackend)};var THREEx=THREEx||{};THREEx.ArVideoInWebgl=function(videoTexture){var _this=this;var geometry=new THREE.PlaneGeometry(2,2);var material=new THREE.MeshBasicMaterial({map:videoTexture});var seethruPlane=new THREE.Mesh(geometry,material);this.object3d=seethruPlane;this.update=function(camera){camera.updateMatrixWorld(true);var position=new THREE.Vector3(-0,0,-20);var position=new THREE.Vector3(-0,0,-20);seethruPlane.position.copy(position);camera.localToWorld(seethruPlane.position);camera.matrixWorld.decompose(camera.position,camera.quaternion,camera.scale);seethruPlane.quaternion.copy(camera.quaternion);var fov=THREE.Math.radToDeg(Math.atan(1/camera.projectionMatrix.elements[5]))*2;
THREEx.ArMarkerCloak.fragmentShader="\n"+" varying vec2 vUv;\n"+" uniform sampler2D texture;\n"+" uniform float opacity;\n"+"\n"+" void main(void){\n"+" vec3 color = texture2D( texture, vUv ).rgb;\n"+"\n"+" gl_FragColor = vec4( color, opacity);\n"+" }";var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkerControls=THREEx.ArMarkerControls=function(context,object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.context=context;this.parameters={size:1,type:"unknown",patternUrl:null,barcodeValue:null,changeMatrixMode:"modelViewMatrix",minConfidence:.6};var possibleValues=["pattern","barcode","unknown"];console.assert(possibleValues.indexOf(this.parameters.type)!==-1,"illegal value",this.parameters.type);var possibleValues=["modelViewMatrix","cameraTransformMatrix"];console.assert(possibleValues.indexOf(this.parameters.changeMatrixMode)!==-1,"illegal value",this.parameters.changeMatrixMode);this.object3d=object3d;this.object3d.matrixAutoUpdate=false;this.object3d.visible=false;setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArMarkerControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}context.addMarker(this);if(_this.context.parameters.trackingBackend==="artoolkit"){this._initArtoolkit()}else if(_this.context.parameters.trackingBackend==="aruco"){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)}else if(_this.context.parameters.trackingBackend==="tango"){this._initTango()}else console.assert(false)};ARjs.MarkerControls.prototype=Object.create(THREEx.ArBaseControls.prototype);ARjs.MarkerControls.prototype.constructor=THREEx.ArMarkerControls;ARjs.MarkerControls.prototype.dispose=function(){this.context.removeMarker(this)};ARjs.MarkerControls.prototype.updateWithModelViewMatrix=function(modelViewMatrix){var markerObject3D=this.object3d;markerObject3D.visible=true;if(this.context.parameters.trackingBackend==="artoolkit"){var tmpMatrix=(new THREE.Matrix4).copy(this.context._artoolkitProjectionAxisTransformMatrix);tmpMatrix.multiply(modelViewMatrix);modelViewMatrix.copy(tmpMatrix)}else if(this.context.parameters.trackingBackend==="aruco"){}else if(this.context.parameters.trackingBackend==="tango"){}else console.assert(false);if(this.context.parameters.trackingBackend!=="tango"){var markerAxisTransformMatrix=(new THREE.Matrix4).makeRotationX(Math.PI/2);modelViewMatrix.multiply(markerAxisTransformMatrix)}if(this.parameters.changeMatrixMode==="modelViewMatrix"){markerObject3D.matrix.copy(modelViewMatrix)}else if(this.parameters.changeMatrixMode==="cameraTransformMatrix"){markerObject3D.matrix.getInverse(modelViewMatrix)}else{console.assert(false)}markerObject3D.matrix.decompose(markerObject3D.position,markerObject3D.quaternion,markerObject3D.scale);this.dispatchEvent({type:"markerFound"})};ARjs.MarkerControls.prototype.name=function(){var name="";name+=this.parameters.type;if(this.parameters.type==="pattern"){var url=this.parameters.patternUrl;var basename=url.replace(/^.*\//g,"");name+=" - "+basename}else if(this.parameters.type==="barcode"){name+=" - "+this.parameters.barcodeValue}else{console.assert(false,"no .name() implemented for this marker controls")}return name};ARjs.MarkerControls.prototype._initArtoolkit=function(){var _this=this;var artoolkitMarkerId=null;var delayedInitTimerId=setInterval(function(){var arController=_this.context.arController;if(arController===null)return;clearInterval(delayedInitTimerId);delayedInitTimerId=null;postInit()},1e3/50);return;function postInit(){var arController=_this.context.arController;console.assert(arController!==null);if(_this.parameters.type==="pattern"){arController.loadMarker(_this.parameters.patternUrl,function(markerId){artoolkitMarkerId=markerId;arController.trackPatternMarkerId(artoolkitMarkerId,_this.parameters.size)})}else if(_this.parameters.type==="barcode"){artoolkitMarkerId=_this.parameters.barcodeValue;arController.trackBarcodeMarkerId(artoolkitMarkerId,_this.parameters.size)}else if(_this.parameters.type==="unknown"){artoolkitMarkerId=null}else{console.log(false,"invalid marker type",_this.parameters.type)}arController.addEventListener("getMarker",function(event){if(event.data.type===artoolkit.PATTERN_MARKER&&_this.parameters.type==="pattern"){if(artoolkitMarkerId===null)return;if(event.data.marker.idPatt===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.BARCODE_MARKER&&_this.parameters.type==="barcode"){if(artoolkitMarkerId===null)return;if(event.data.marker.idMatrix===artoolkitMarkerId)onMarkerFound(event)}else if(event.data.type===artoolkit.UNKNOWN_MARKER&&_this.parameters.type==="unknown"){onMarkerFound(event)}})}function onMarkerFound(event){if(event.data.type===artoolkit.PATTERN_MARKER&&event.data.marker.cfPatt<_this.parameters.minConfidence)return;if(event.data.type===artoolkit.BARCODE_MARKER&&event.data.marker.cfMatt<_this.parameters.minConfidence)return;var modelViewMatrix=(new THREE.Matrix4).fromArray(event.data.matrix);_this.updateWithModelViewMatrix(modelViewMatrix)}};ARjs.MarkerControls.prototype._initAruco=function(){this._arucoPosit=new POS.Posit(this.parameters.size,_this.context.arucoContext.canvas.width)};ARjs.MarkerControls.prototype._initTango=function(){var _this=this;console.log("init tango ArMarkerControls")};var THREEx=THREEx||{};THREEx.ArMarkerHelper=function(markerControls){this.object3d=new THREE.Group;var mesh=new THREE.AxisHelper;this.object3d.add(mesh);var text=markerControls.id;var canvas=document.createElement("canvas");canvas.width=64;canvas.height=64;var context=canvas.getContext("2d");var texture=new THREE.CanvasTexture(canvas);context.font="48px monospace";context.fillStyle="rgba(192,192,255, 0.5)";context.fillRect(0,0,canvas.width,canvas.height);context.fillStyle="darkblue";context.fillText(text,canvas.width/4,3*canvas.height/4);texture.needsUpdate=true;var geometry=new THREE.PlaneGeometry(1,1);var material=new THREE.MeshBasicMaterial({map:texture,transparent:true});var mesh=new THREE.Mesh(geometry,material);mesh.rotation.x=-Math.PI/2;this.object3d.add(mesh)};var THREEx=THREEx||{};THREEx.ArSmoothedControls=function(object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);this.object3d.visible=false;this._lastLerpStepAt=null;this._visibleStartedAt=null;this._unvisibleStartedAt=null;parameters=parameters||{};this.parameters={lerpPosition:.8,lerpQuaternion:.2,lerpScale:.7,lerpStepDelay:1/60,minVisibleDelay:0,minUnvisibleDelay:.2};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArSmoothedControls: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};THREEx.ArSmoothedControls.prototype=Object.create(THREEx.ArBaseControls.prototype);THREEx.ArSmoothedControls.prototype.constructor=THREEx.ArSmoothedControls;THREEx.ArSmoothedControls.prototype.update=function(targetObject3d){var object3d=this.object3d;var parameters=this.parameters;var wasVisible=object3d.visible;var present=performance.now()/1e3;if(targetObject3d.visible===false)this._visibleStartedAt=null;if(targetObject3d.visible===true)this._unvisibleStartedAt=null;if(targetObject3d.visible===true&&this._visibleStartedAt===null)this._visibleStartedAt=present;if(targetObject3d.visible===false&&this._unvisibleStartedAt===null)this._unvisibleStartedAt=present;if(wasVisible===false&&targetObject3d.visible===true){var visibleFor=present-this._visibleStartedAt;if(visibleFor>=this.parameters.minVisibleDelay){object3d.visible=true;snapDirectlyToTarget()}}if(wasVisible===true&&targetObject3d.visible===false){var unvisibleFor=present-this._unvisibleStartedAt;if(unvisibleFor>=this.parameters.minUnvisibleDelay){object3d.visible=false}}if(this._lastLerpStepAt===null){applyOneSlerpStep();this._lastLerpStepAt=present}else{var nStepsToDo=Math.floor((present-this._lastLerpStepAt)/this.parameters.lerpStepDelay);for(var i=0;i<nStepsToDo;i++){applyOneSlerpStep();this._lastLerpStepAt+=this.parameters.lerpStepDelay}}if(false){snapDirectlyToTarget()}this.object3d.updateMatrix();if(wasVisible===false&&object3d.visible===true){this.dispatchEvent({type:"becameVisible"})}if(wasVisible===true&&object3d.visible===false){this.dispatchEvent({type:"becameUnVisible"})}return;function snapDirectlyToTarget(){object3d.position.copy(targetObject3d.position);object3d.quaternion.copy(targetObject3d.quaternion);object3d.scale.copy(targetObject3d.scale)}function applyOneSlerpStep(){object3d.position.lerp(targetObject3d.position,parameters.lerpPosition);object3d.quaternion.slerp(targetObject3d.quaternion,parameters.lerpQuaternion);object3d.scale.lerp(targetObject3d.scale,parameters.lerpScale)}};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Context=THREEx.ArToolkitContext=function(parameters){var _this=this;_this._updatedAt=null;this.parameters={trackingBackend:"artoolkit",debug:false,detectionMode:"mono",matrixCodeType:"3x3",cameraParametersUrl:ARjs.Context.baseURL+"parameters/camera_para.dat",maxDetectionRate:60,canvasWidth:640,canvasHeight:480,patternRatio:.5,imageSmoothingEnabled:false};console.assert(["artoolkit","aruco","tango"].indexOf(this.parameters.trackingBackend)!==-1,"invalid parameter trackingBackend",this.parameters.trackingBackend);console.assert(["color","color_and_matrix","mono","mono_and_matrix"].indexOf(this.parameters.detectionMode)!==-1,"invalid parameter detectionMode",this.parameters.detectionMode);this.arController=null;this.arucoContext=null;_this.initialized=false;this._arMarkersControls=[];setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitContext: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};Object.assign(ARjs.Context.prototype,THREE.EventDispatcher.prototype);ARjs.Context.baseURL="https://jeromeetienne.github.io/AR.js/three.js/";ARjs.Context.REVISION="1.6.
2
";ARjs.Context.createDefaultCamera=function(trackingBackend){console.assert(false,"use ARjs.Utils.createDefaultCamera instead");if(trackingBackend==="artoolkit"){var camera=new THREE.Camera}else if(trackingBackend==="aruco"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else if(trackingBackend==="tango"){var camera=new THREE.PerspectiveCamera(42,renderer.domElement.width/renderer.domElement.height,.01,100)}else console.assert(false);return camera};ARjs.Context.prototype.init=function(onCompleted){var _this=this;if(this.parameters.trackingBackend==="artoolkit"){this._initArtoolkit(done)}else if(this.parameters.trackingBackend==="aruco"){this._initAruco(done)}else if(this.parameters.trackingBackend==="tango"){this._initTango(done)}else console.assert(false);return;function done(){_this.dispatchEvent({type:"initialized"});_this.initialized=true;onCompleted&&onCompleted()}};ARjs.Context.prototype.update=function(srcElement){if(this.parameters.trackingBackend==="artoolkit"&&this.arController===null)return false;var present=performance.now();if(this._updatedAt!==null&&present-this._updatedAt<1e3/this.parameters.maxDetectionRate){return false}this._updatedAt=present;this._arMarkersControls.forEach(function(markerControls){markerControls.object3d.visible=false});if(this.parameters.trackingBackend==="artoolkit"){this._updateArtoolkit(srcElement)}else if(this.parameters.trackingBackend==="aruco"){this._updateAruco(srcElement)}else if(this.parameters.trackingBackend==="tango"){this._updateTango(srcElement)}else{console.assert(false)}this.dispatchEvent({type:"sourceProcessed"});return true};ARjs.Context.prototype.addMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);this._arMarkersControls.push(arMarkerControls)};ARjs.Context.prototype.removeMarker=function(arMarkerControls){console.assert(arMarkerControls instanceof THREEx.ArMarkerControls);var index=this.arMarkerControlss.indexOf(artoolkitMarker);console.assert(index!==index);this._arMarkersControls.splice(index,1)};ARjs.Context.prototype._initArtoolkit=function(onCompleted){var _this=this;this._artoolkitProjectionAxisTransformMatrix=new THREE.Matrix4;this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationY(Math.PI));this._artoolkitProjectionAxisTransformMatrix.multiply((new THREE.Matrix4).makeRotationZ(Math.PI));var cameraParameters=new ARCameraParam(_this.parameters.cameraParametersUrl,function(){var arController=new ARController(_this.parameters.canvasWidth,_this.parameters.canvasHeight,cameraParameters);_this.arController=arController;arController.ctx.mozImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.webkitImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.msImageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;arController.ctx.imageSmoothingEnabled=_this.parameters.imageSmoothingEnabled;if(_this.parameters.debug===true){arController.debugSetup();arController.canvas.style.position="absolute";arController.canvas.style.top="0px";arController.canvas.style.opacity="0.6";arController.canvas.style.pointerEvents="none";arController.canvas.style.zIndex="-1"}var detectionModes={color:artoolkit.AR_TEMPLATE_MATCHING_COLOR,color_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX,mono:artoolkit.AR_TEMPLATE_MATCHING_MONO,mono_and_matrix:artoolkit.AR_TEMPLATE_MATCHING_MONO_AND_MATRIX};var detectionMode=detectionModes[_this.parameters.detectionMode];console.assert(detectionMode!==undefined);arController.setPatternDetectionMode(detectionMode);var matrixCodeTypes={"3x3":artoolkit.AR_MATRIX_CODE_3x3,"3x3_HAMMING63":artoolkit.AR_MATRIX_CODE_3x3_HAMMING63,"3x3_PARITY65":artoolkit.AR_MATRIX_CODE_3x3_PARITY65,"4x4":artoolkit.AR_MATRIX_CODE_4x4,"4x4_BCH_13_9_3":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_9_3,"4x4_BCH_13_5_5":artoolkit.AR_MATRIX_CODE_4x4_BCH_13_5_5};var matrixCodeType=matrixCodeTypes[_this.parameters.matrixCodeType];console.assert(matrixCodeType!==undefined);arController.setMatrixCodeType(matrixCodeType);arController.setPattRatio(_this.parameters.patternRatio);onCompleted()});return this};ARjs.Context.prototype.getProjectionMatrix=function(srcElement){console.assert(this.parameters.trackingBackend==="artoolkit");console.assert(this.arController,"arController MUST be initialized to call this function");var projectionMatrixArr=this.arController.getCameraMatrix();var projectionMatrix=(new THREE.Matrix4).fromArray(projectionMatrixArr);projectionMatrix.multiply(this._artoolkitProjectionAxisTransformMatrix);return projectionMatrix};ARjs.Context.prototype._updateArtoolkit=function(srcElement){this.arController.process(srcElement)};ARjs.Context.prototype._initAruco=function(onCompleted){this.arucoContext=new THREEx.ArucoContext;this.arucoContext.canvas.width=this.parameters.canvasWidth;this.arucoContext.canvas.height=this.parameters.canvasHeight;var context=this.arucoContext.canvas.getContext("2d");context.webkitImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.msImageSmoothingEnabled=this.parameters.imageSmoothingEnabled;context.imageSmoothingEnabled=this.parameters.imageSmoothingEnabled;setTimeout(function(){onCompleted()},0)};ARjs.Context.prototype._updateAruco=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var detectedMarkers=this.arucoContext.detect(srcElement);detectedMarkers.forEach(function(detectedMarker){var foundControls=null;for(var i=0;i<arMarkersControls.length;i++){console.assert(arMarkersControls[i].parameters.type==="barcode");if(arMarkersControls[i].parameters.barcodeValue===detectedMarker.id){foundControls=arMarkersControls[i];break}}if(foundControls===null)return;var tmpObject3d=new THREE.Object3D;_this.arucoContext.updateObject3D(tmpObject3d,foundControls._arucoPosit,foundControls.parameters.size,detectedMarker);tmpObject3d.updateMatrix();foundControls.updateWithModelViewMatrix(tmpObject3d.matrix)})};ARjs.Context.prototype._initTango=function(onCompleted){var _this=this;if(navigator.getVRDisplays){}else if(navigator.getVRDevices){alert("Your browser supports WebVR but not the latest version. See <a href='http://webvr.info'>webvr.info</a> for more info.")}else{alert("Your browser does not support WebVR. See <a href='http://webvr.info'>webvr.info</a> for assistance.")}this._tangoContext={vrDisplay:null,vrPointCloud:null,frameData:new VRFrameData};navigator.getVRDisplays().then(function(vrDisplays){if(vrDisplays.length===0)alert("no vrDisplays available");var vrDisplay=_this._tangoContext.vrDisplay=vrDisplays[0];console.log("vrDisplays.displayName :",vrDisplay.displayName);if(vrDisplay.displayName==="Tango VR Device"){_this._tangoContext.vrPointCloud=new THREE.WebAR.VRPointCloud(vrDisplay,true)}onCompleted()})};ARjs.Context.prototype._updateTango=function(srcElement){var _this=this;var arMarkersControls=this._arMarkersControls;var tangoContext=this._tangoContext;var vrDisplay=this._tangoContext.vrDisplay;if(vrDisplay===null)return;if(vrDisplay.displayName==="Tango VR Device"){var showPointCloud=true;var pointsToSkip=0;_this._tangoContext.vrPointCloud.update(showPointCloud,pointsToSkip,true)}if(this._arMarkersControls.length===0)return;var foundControls=this._arMarkersControls[0];var frameData=this._tangoContext.frameData;vrDisplay.getFrameData(frameData);if(frameData.pose.position===null)return;if(frameData.pose.orientation===null)return;var position=(new THREE.Vector3).fromArray(frameData.pose.position);var quaternion=(new THREE.Quaternion).fromArray(frameData.pose.orientation);var scale=new THREE.Vector3(1,1,1);var cameraTransformMatrix=(new THREE.Matrix4).compose(position,quaternion,scale);var modelViewMatrix=new THREE.Matrix4;modelViewMatrix.getInverse(cameraTransformMatrix);foundControls.updateWithModelViewMatrix(modelViewMatrix)};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Profile=THREEx.ArToolkitProfile=function(){this.reset();this.performance("default")};ARjs.Profile.prototype._guessPerformanceLabel=function(){var isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/webOS/i)||navigator.userAgent.match(/iPhone/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPod/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Windows Phone/i)?true:false;if(isMobile===true){return"phone-normal"}return"desktop-normal"};ARjs.Profile.prototype.reset=function(){this.sourceParameters={sourceType:"webcam"};this.contextParameters={cameraParametersUrl:THREEx.ArToolkitContext.baseURL+"../data/data/camera_para.dat",detectionMode:"mono"};this.defaultMarkerParameters={type:"pattern",patternUrl:THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro",changeMatrixMode:"modelViewMatrix"};return this};ARjs.Profile.prototype.performance=function(label){if(label==="default"){label=this._guessPerformanceLabel()}if(label==="desktop-fast"){this.contextParameters.canvasWidth=640*3;this.contextParameters.canvasHeight=480*3;this.contextParameters.maxDetectionRate=30}else if(label==="desktop-normal"){this.contextParameters.canvasWidth=640;this.contextParameters.canvasHeight=480;this.contextParameters.maxDetectionRate=60}else if(label==="phone-normal"){this.contextParameters.canvasWidth=80*4;this.contextParameters.canvasHeight=60*4;this.contextParameters.maxDetectionRate=30}else if(label==="phone-slow"){this.contextParameters.canvasWidth=80*3;this.contextParameters.canvasHeight=60*3;this.contextParameters.maxDetectionRate=30}else{console.assert(false,"unknonwn label "+label)}return this};ARjs.Profile.prototype.defaultMarker=function(trackingBackend){trackingBackend=trackingBackend||this.contextParameters.trackingBackend;if(trackingBackend==="artoolkit"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="pattern";this.defaultMarkerParameters.patternUrl=THREEx.ArToolkitContext.baseURL+"../data/data/patt.hiro"}else if(trackingBackend==="aruco"){this.contextParameters.detectionMode="mono";this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else if(trackingBackend==="tango"){this.defaultMarkerParameters.type="barcode";this.defaultMarkerParameters.barcodeValue=1001}else console.assert(false);return this};ARjs.Profile.prototype.sourceWebcam=function(){this.sourceParameters.sourceType="webcam";delete this.sourceParameters.sourceUrl;return this};ARjs.Profile.prototype.sourceVideo=function(url){this.sourceParameters.sourceType="video";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.sourceImage=function(url){this.sourceParameters.sourceType="image";this.sourceParameters.sourceUrl=url;return this};ARjs.Profile.prototype.trackingBackend=function(trackingBackend){console.warn("stop profile.trackingBackend() obsolete function. use .trackingMethod instead");this.contextParameters.trackingBackend=trackingBackend;return this};ARjs.Profile.prototype.changeMatrixMode=function(changeMatrixMode){this.defaultMarkerParameters.changeMatrixMode=changeMatrixMode;return this};ARjs.Profile.prototype.trackingMethod=function(trackingMethod){var data=ARjs.Utils.parseTrackingMethod(trackingMethod);this.defaultMarkerParameters.markersAreaEnabled=data.markersAreaEnabled;this.contextParameters.trackingBackend=data.trackingBackend;return this};ARjs.Profile.prototype.checkIfValid=function(){if(this.contextParameters.trackingBackend==="tango"){this.sourceImage(THREEx.ArToolkitContext.baseURL+"../data/images/img.jpg")}return this};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.Source=THREEx.ArToolkitSource=function(parameters){var _this=this;this.ready=false;this.domElement=null;this.parameters={sourceType:"webcam",sourceUrl:null,deviceId:null,sourceWidth:640,sourceHeight:480,displayWidth:640,displayHeight:480};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.ArToolkitSource: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}};ARjs.Source.prototype.init=function(onReady,onError){var _this=this;if(this.parameters.sourceType==="image"){var domElement=this._initSourceImage(onSourceReady,onError)}else if(this.parameters.sourceType==="video"){var domElement=this._initSourceVideo(onSourceReady,onError)}else if(this.parameters.sourceType==="webcam"){var domElement=this._initSourceWebcam(onSourceReady,onError)}else{console.assert(false)}this.domElement=domElement;this.domElement.style.position="absolute";this.domElement.style.top="0px";this.domElement.style.left="0px";this.domElement.style.zIndex="-2";return this;function onSourceReady(){document.body.appendChild(_this.domElement);_this.ready=true;onReady&&onReady()}};ARjs.Source.prototype._initSourceImage=function(onReady){var domElement=document.createElement("img");domElement.src=this.parameters.sourceUrl;domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.naturalWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceVideo=function(onReady){var domElement=document.createElement("video");domElement.src=this.parameters.sourceUrl;domElement.style.objectFit="initial";domElement.autoplay=true;domElement.webkitPlaysinline=true;domElement.controls=false;domElement.loop=true;domElement.muted=true;document.body.addEventListener("click",function onClick(){document.body.removeEventListener("click",onClick);domElement.play()});domElement.width=this.parameters.sourceWidth;domElement.height=this.parameters.sourceHeight;domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50);return domElement};ARjs.Source.prototype._initSourceWebcam=function(onReady,onError){var _this=this;onError=onError||function(error){alert("Webcam Error\nName: "+error.name+"\nMessage: "+error.message)};var domElement=document.createElement("video");domElement.setAttribute("autoplay","");domElement.setAttribute("muted","");domElement.setAttribute("playsinline","");domElement.style.width=this.parameters.displayWidth+"px";domElement.style.height=this.parameters.displayHeight+"px";if(navigator.mediaDevices===undefined||navigator.mediaDevices.enumerateDevices===undefined||navigator.mediaDevices.getUserMedia===undefined){if(navigator.mediaDevices===undefined)var fctName="navigator.mediaDevices";else if(navigator.mediaDevices.enumerateDevices===undefined)var fctName="navigator.mediaDevices.enumerateDevices";else if(navigator.mediaDevices.getUserMedia===undefined)var fctName="navigator.mediaDevices.getUserMedia";else console.assert(false);onError({name:"",message:"WebRTC issue-! "+fctName+" not present in your browser"});return null}navigator.mediaDevices.enumerateDevices().then(function(devices){var userMediaConstraints={audio:false,video:{facingMode:"environment",width:{ideal:_this.parameters.sourceWidth},height:{ideal:_this.parameters.sourceHeight}}};if(null!==_this.parameters.deviceId){userMediaConstraints.video.deviceId={exact:_this.parameters.deviceId}}navigator.mediaDevices.getUserMedia(userMediaConstraints).then(function success(stream){domElement.srcObject=stream;document.body.addEventListener("click",function(){domElement.play()});var interval=setInterval(function(){if(!domElement.videoWidth)return;onReady();clearInterval(interval)},1e3/50)}).catch(function(error){onError({name:error.name,message:error.message})})}).catch(function(error){onError({message:error.message})});return domElement};ARjs.Source.prototype.hasMobileTorch=function(){var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false)return false;if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];if(videoTrack.getCapabilities===undefined)return false;var capabilities=videoTrack.getCapabilities();return capabilities.torch?true:false};ARjs.Source.prototype.toggleMobileTorch=function(){console.assert(this.hasMobileTorch()===true);var stream=arToolkitSource.domElement.srcObject;if(stream instanceof MediaStream===false){alert("enabling mobile torch is available only on webcam");return}if(this._currentTorchStatus===undefined){this._currentTorchStatus=false}var videoTrack=stream.getVideoTracks()[0];var capabilities=videoTrack.getCapabilities();if(!capabilities.torch){alert("no mobile torch is available on your camera");return}this._currentTorchStatus=this._currentTorchStatus===false?true:false;videoTrack.applyConstraints({advanced:[{torch:this._currentTorchStatus}]}).catch(function(error){console.log(error)})};ARjs.Source.prototype.domElementWidth=function(){return parseInt(this.domElement.style.width)};ARjs.Source.prototype.domElementHeight=function(){return parseInt(this.domElement.style.height)};ARjs.Source.prototype.onResizeElement=function(){var _this=this;var screenWidth=window.innerWidth;var screenHeight=window.innerHeight;console.assert(arguments.length===0);if(this.domElement.nodeName==="IMG"){var sourceWidth=this.domElement.naturalWidth;var sourceHeight=this.domElement.naturalHeight}else if(this.domElement.nodeName==="VIDEO"){var sourceWidth=this.domElement.videoWidth;var sourceHeight=this.domElement.videoHeight}else{console.assert(false)}var sourceAspect=sourceWidth/sourceHeight;var screenAspect=screenWidth/screenHeight;if(screenAspect<sourceAspect){var newWidth=sourceAspect*screenHeight;this.domElement.style.width=newWidth+"px";this.domElement.style.marginLeft=-(newWidth-screenWidth)/2+"px";this.domElement.style.height=screenHeight+"px";this.domElement.style.marginTop="0px"}else{var newHeight=1/(sourceAspect/screenWidth);this.domElement.style.height=newHeight+"px";this.domElement.style.marginTop=-(newHeight-screenHeight)/2+"px";this.domElement.style.width=screenWidth+"px";this.domElement.style.marginLeft="0px"}};ARjs.Source.prototype.copyElementSizeTo=function(otherElement){if(window.innerWidth>window.innerHeight){otherElement.style.width=this.domElement.style.width;otherElement.style.height=this.domElement.style.height;otherElement.style.marginLeft=this.domElement.style.marginLeft;otherElement.style.marginTop=this.domElement.style.marginTop}else{otherElement.style.height=this.domElement.style.height;otherElement.style.width=parseInt(otherElement.style.height)*4/3+"px";otherElement.style.marginLeft=(window.innerWidth-parseInt(otherElement.style.width))/2+"px";otherElement.style.marginTop=0}};ARjs.Source.prototype.copySizeTo=function(){console.warn("obsolete function arToolkitSource.copySizeTo. Use arToolkitSource.copyElementSizeTo");this.copyElementSizeTo.apply(this,arguments)};ARjs.Source.prototype.onResize=function(arToolkitContext,renderer,camera){if(arguments.length!==3){console.warn("obsolete function arToolkitSource.onResize. Use arToolkitSource.onResizeElement");return this.onResizeElement.apply(this,arguments)}var trackingBackend=arToolkitContext.parameters.trackingBackend;if(trackingBackend==="artoolkit"){this.onResizeElement();var isAframe=renderer.domElement.dataset.aframeCanvas?true:false;if(isAframe===false){this.copyElementSizeTo(renderer.domElement)}else{}if(arToolkitContext.arController!==null){this.copyElementSizeTo(arToolkitContext.arController.canvas)}}else if(trackingBackend==="aruco"){this.onResizeElement();this.copyElementSizeTo(renderer.domElement);this.copyElementSizeTo(arToolkitContext.arucoContext.canvas)}else if(trackingBackend==="tango"){renderer.setSize(window.innerWidth,window.innerHeight)}else console.assert(false,"unhandled trackingBackend "+trackingBackend);if(trackingBackend==="artoolkit"){if(arToolkitContext.arController!==null){camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix())}}else if(trackingBackend==="aruco"){camera.aspect=renderer.domElement.width/renderer.domElement.height;camera.updateProjectionMatrix()}else if(trackingBackend==="tango"){var vrDisplay=arToolkitContext._tangoContext.vrDisplay;if(vrDisplay&&vrDisplay.displayName==="Tango VR Device")THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay,camera)}else console.assert(false,"unhandled trackingBackend "+trackingBackend)};var THREEx=THREEx||{};THREEx.ArVideoInWebgl=function(videoTexture){var _this=this;var geometry=new THREE.PlaneGeometry(2,2);var material=new THREE.MeshBasicMaterial({map:videoTexture});var seethruPlane=new THREE.Mesh(geometry,material);this.object3d=seethruPlane;this.update=function(camera){camera.updateMatrixWorld(true);var position=new THREE.Vector3(-0,0,-20);var position=new THREE.Vector3(-0,0,-20);seethruPlane.position.copy(position);camera.localToWorld(seethruPlane.position);camera.matrixWorld.decompose(camera.position,camera.quaternion,camera.scale);seethruPlane.quaternion.copy(camera.quaternion);var fov=THREE.Math.radToDeg(Math.atan(1/camera.projectionMatrix.elements[5]))*2;
var elementWidth=parseFloat(arToolkitSource.domElement.style.width.replace(/px$/,""),10);var elementHeight=parseFloat(arToolkitSource.domElement.style.height.replace(/px$/,""),10);var aspect=elementWidth/elementHeight;seethruPlane.scale.y=Math.tan(THREE.Math.DEG2RAD*fov/2)*position.length();seethruPlane.scale.x=seethruPlane.scale.y*aspect}};var THREEx=THREEx||{};THREEx.HitTestingPlane=function(sourceElement){this._sourceElement=sourceElement;this._pickingScene=new THREE.Scene;var geometry=new THREE.PlaneGeometry(20,20,19,19).rotateX(-Math.PI/2);var material=new THREE.MeshBasicMaterial({wireframe:true});this._pickingPlane=new THREE.Mesh(geometry,material);this._pickingScene.add(this._pickingPlane);var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);this._pickingCamera=new THREE.PerspectiveCamera(42,fullWidth/fullHeight,.1,30)};THREEx.HitTestingPlane.prototype.update=function(camera,pickingRoot,changeMatrixMode){this.onResize();if(changeMatrixMode==="modelViewMatrix"){var pickingPlane=this._pickingPlane;pickingRoot.parent.updateMatrixWorld();pickingPlane.matrix.copy(pickingRoot.parent.matrixWorld);pickingPlane.matrix.decompose(pickingPlane.position,pickingPlane.quaternion,pickingPlane.scale)}else if(changeMatrixMode==="cameraTransformMatrix"){var pickingCamera=this._pickingCamera;camera.updateMatrixWorld();pickingCamera.matrix.copy(camera.matrixWorld);pickingCamera.matrix.decompose(pickingCamera.position,pickingCamera.quaternion,pickingCamera.scale)}else console.assert(false)};THREEx.HitTestingPlane.prototype.onResize=function(){var sourceElement=this._sourceElement;var pickingCamera=this._pickingCamera;var fullWidth=parseInt(sourceElement.style.width);var fullHeight=parseInt(sourceElement.style.height);pickingCamera.aspect=fullWidth/fullHeight;pickingCamera.updateProjectionMatrix()};THREEx.HitTestingPlane.prototype.test=function(mouseX,mouseY){mouseX=(mouseX-.5)*2;mouseY=-(mouseY-.5)*2;this._pickingScene.updateMatrixWorld(true);var raycaster=new THREE.Raycaster;var mouseVector3=new THREE.Vector3(mouseX,mouseY,1);raycaster.setFromCamera(mouseVector3,this._pickingCamera);var intersects=raycaster.intersectObjects([this._pickingPlane]);if(intersects.length===0)return null;var position=this._pickingPlane.worldToLocal(intersects[0].point.clone());var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3(1,1,1);return{position:position,quaternion:quaternion,scale:scale}};THREEx.HitTestingPlane.prototype.renderDebug=function(renderer){renderer.render(this._pickingScene,this._pickingCamera)};var THREEx=THREEx||{};THREEx.HitTestingTango=function(arContext){this._arContext=arContext;this.boundingSphereRadius=.01;this.resultScale=new THREE.Vector3(1,1,1).multiplyScalar(1)};THREEx.HitTestingTango.prototype.update=function(){};THREEx.HitTestingTango.prototype.test=function(mouseX,mouseY){var vrDisplay=this._arContext._tangoContext.vrDisplay;if(vrDisplay===null)return null;if(vrDisplay.displayName!=="Tango VR Device")return null;var pointAndPlane=vrDisplay.getPickingPointAndPlaneInPointCloud(mouseX,mouseY);if(pointAndPlane==null){console.warn("Could not retrieve the correct point and plane.");return null}var boundingSphereRadius=.01;var object3d=new THREE.Object3D;THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud(pointAndPlane,object3d,this.boundingSphereRadius);object3d.rotateZ(-Math.PI/2);var result={position:object3d.position,quaternion:object3d.quaternion,scale:this.resultScale};return result};var ARjs=ARjs||{};ARjs.Anchor=function(arSession,markerParameters){var _this=this;var arContext=arSession.arContext;var scene=arSession.parameters.scene;var camera=arSession.parameters.camera;this.arSession=arSession;this.parameters=markerParameters;console.log("ARjs.Anchor -","changeMatrixMode:",this.parameters.changeMatrixMode,"/ markersAreaEnabled:",markerParameters.markersAreaEnabled);var markerRoot=new THREE.Group;scene.add(markerRoot);if(markerParameters.changeMatrixMode==="modelViewMatrix"){var controlledObject=markerRoot}else if(markerParameters.changeMatrixMode==="cameraTransformMatrix"){var controlledObject=camera}else console.assert(false);if(markerParameters.markersAreaEnabled===false){var markerControls=new THREEx.ArMarkerControls(arContext,controlledObject,markerParameters);this.controls=markerControls}else{console.assert(arContext.parameters.trackingBackend==="artoolkit"||arContext.parameters.trackingBackend==="aruco");if(location.hash.substring(1).startsWith("markers-page-resolution=")===true){var markerPageResolution=location.hash.substring(1);var matches=markerPageResolution.match(/markers-page-resolution=(\d+)x(\d+)/);console.assert(matches.length===3);var resolutionW=parseInt(matches[1]);var resolutionH=parseInt(matches[2]);var arContext=arSession.arContext;ARjs.MarkersAreaUtils.storeMarkersAreaFileFromResolution(arContext.parameters.trackingBackend,resolutionW,resolutionH)}if(localStorage.getItem("ARjsMultiMarkerFile")===null){ARjs.MarkersAreaUtils.storeDefaultMultiMarkerFile(arContext.parameters.trackingBackend)}console.assert(localStorage.getItem("ARjsMultiMarkerFile")!==null);var multiMarkerFile=localStorage.getItem("ARjsMultiMarkerFile");if(markerParameters.changeMatrixMode==="modelViewMatrix"){var parent3D=scene}else if(markerParameters.changeMatrixMode==="cameraTransformMatrix"){var parent3D=camera}else console.assert(false);var multiMarkerControls=ARjs.MarkersAreaControls.fromJSON(arContext,parent3D,controlledObject,multiMarkerFile);this.controls=multiMarkerControls;multiMarkerControls.parameters.changeMatrixMode=markerParameters.changeMatrixMode;var markerHelpers=[];multiMarkerControls.subMarkersControls.forEach(function(subMarkerControls){var markerHelper=new THREEx.ArMarkerHelper(subMarkerControls);markerHelper.object3d.visible=false;subMarkerControls.object3d.add(markerHelper.object3d);markerHelpers.push(markerHelper)});this.markersArea={};this.markersArea.setSubMarkersVisibility=function(visible){markerHelpers.forEach(function(markerHelper){markerHelper.object3d.visible=visible})}}this.object3d=new THREE.Group;var shouldBeSmoothed=true;if(arContext.parameters.trackingBackend==="tango")shouldBeSmoothed=false;if(shouldBeSmoothed===true){var smoothedRoot=new THREE.Group;scene.add(smoothedRoot);var smoothedControls=new THREEx.ArSmoothedControls(smoothedRoot);smoothedRoot.add(this.object3d)}else{markerRoot.add(this.object3d)}this.update=function(){_this.object3d.visible=_this.object3d.parent.visible;if(smoothedControls!==undefined){if(multiMarkerControls!==undefined){multiMarkerControls.updateSmoothedControls(smoothedControls)}smoothedControls.update(markerRoot)}}};var ARjs=ARjs||{};ARjs.SessionDebugUI=function(arSession,tangoPointCloud){var trackingBackend=arSession.arContext.parameters.trackingBackend;this.domElement=document.createElement("div");this.domElement.style.color="rgba(0,0,0,0.9)";this.domElement.style.backgroundColor="rgba(127,127,127,0.5)";this.domElement.style.display="inline-block";this.domElement.style.padding="0.5em";this.domElement.style.margin="0.5em";this.domElement.style.textAlign="left";var domElement=document.createElement("span");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.innerHTML="<b>trackingBackend</b> : "+trackingBackend;if(ARjs.SessionDebugUI.AugmentedWebsiteURL){var domElement=document.createElement("a");domElement.innerHTML="Share on augmented-websites";domElement.style.display="block";domElement.href=ARjs.SessionDebugUI.AugmentedWebsiteURL+"?"+location.href;this.domElement.appendChild(domElement)}if(trackingBackend==="tango"&&tangoPointCloud){var domElement=document.createElement("button");this.domElement.appendChild(domElement);domElement.id="buttonTangoTogglePointCloud";domElement.innerHTML="toggle-point-cloud";domElement.href="javascript:void(0)";domElement.addEventListener("click",function(){var scene=arSession.parameters.scene;if(tangoPointCloud.object3d.parent){scene.remove(tangoPointCloud.object3d)}else{scene.add(tangoPointCloud.object3d)}})}};ARjs.SessionDebugUI.AugmentedWebsiteURL="https://webxr.io/augmented-website";ARjs.AnchorDebugUI=function(arAnchor){var _this=this;var arSession=arAnchor.arSession;var trackingBackend=arSession.arContext.parameters.trackingBackend;this.domElement=document.createElement("div");this.domElement.style.color="rgba(0,0,0,0.9)";this.domElement.style.backgroundColor="rgba(127,127,127,0.5)";this.domElement.style.display="inline-block";this.domElement.style.padding="0.5em";this.domElement.style.margin="0.5em";this.domElement.style.textAlign="left";var domElement=document.createElement("span");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.innerHTML="<b>markersAreaEnabled</b> :"+arAnchor.parameters.markersAreaEnabled;if(arAnchor.parameters.markersAreaEnabled){var domElement=document.createElement("button");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.id="buttonToggleMarkerHelpers";domElement.innerHTML="toggle-marker-helper";domElement.href="javascript:void(0)";var subMarkerHelpersVisible=false;domElement.addEventListener("click",function(){subMarkerHelpersVisible=subMarkerHelpersVisible?false:true;arAnchor.markersArea.setSubMarkersVisibility(subMarkerHelpersVisible)})}if(arAnchor.parameters.markersAreaEnabled){var domElement=document.createElement("button");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.id="buttonMarkersAreaLearner";domElement.innerHTML="Learn-new-marker-area";domElement.href="javascript:void(0)";domElement.addEventListener("click",function(){if(ARjs.AnchorDebugUI.MarkersAreaLearnerURL!==null){var learnerURL=ARjs.AnchorDebugUI.MarkersAreaLearnerURL}else{var learnerURL=ARjs.Context.baseURL+"examples/multi-markers/examples/learner.html"}ARjs.MarkersAreaUtils.navigateToLearnerPage(learnerURL,trackingBackend)})}if(arAnchor.parameters.markersAreaEnabled){var domElement=document.createElement("button");domElement.style.display="block";this.domElement.appendChild(domElement);domElement.id="buttonMarkersAreaReset";domElement.innerHTML="Reset-marker-area";domElement.href="javascript:void(0)";domElement.addEventListener("click",function(){ARjs.MarkersAreaUtils.storeDefaultMultiMarkerFile(trackingBackend);location.reload()})}};ARjs.AnchorDebugUI.MarkersAreaLearnerURL=null;var ARjs=ARjs||{};ARjs.HitTesting=function(arSession){var _this=this;var arContext=arSession.arContext;var trackingBackend=arContext.parameters.trackingBackend;this.enabled=true;this._arSession=arSession;this._hitTestingPlane=null;this._hitTestingTango=null;if(trackingBackend==="tango"){_this._hitTestingTango=new THREEx.HitTestingTango(arContext)}else{_this._hitTestingPlane=new THREEx.HitTestingPlane(arSession.arSource.domElement)}};ARjs.HitTesting.prototype.update=function(camera,pickingRoot,changeMatrixMode){if(this.enabled===false)return;if(this._hitTestingTango!==null){this._hitTestingTango.update()}else if(this._hitTestingPlane!==null){this._hitTestingPlane.update(camera,pickingRoot,changeMatrixMode)}else console.assert(false)};ARjs.HitTesting.prototype.testDomEvent=function(domEvent){var trackingBackend=this._arSession.arContext.parameters.trackingBackend;var arSource=this._arSession.arSource;if(this.enabled===false)return[];if(trackingBackend==="tango"){var mouseX=domEvent.pageX/window.innerWidth;var mouseY=domEvent.pageY/window.innerHeight}else{var mouseX=domEvent.clientX/arSource.domElementWidth();var mouseY=domEvent.clientY/arSource.domElementHeight()}return this.test(mouseX,mouseY)};ARjs.HitTesting.prototype.test=function(mouseX,mouseY){var arContext=this._arSession.arContext;var trackingBackend=arContext.parameters.trackingBackend;var hitTestResults=[];if(this.enabled===false)return[];var result=null;if(trackingBackend==="tango"){var result=this._hitTestingTango.test(mouseX,mouseY)}else{var result=this._hitTestingPlane.test(mouseX,mouseY)}if(result===null)return hitTestResults;var hitTestResult=new ARjs.HitTesting.Result(result.position,result.quaternion,result.scale);hitTestResults.push(hitTestResult);return hitTestResults};ARjs.HitTesting.Result=function(position,quaternion,scale){this.position=position;this.quaternion=quaternion;this.scale=scale};ARjs.HitTesting.Result.prototype.apply=function(object3d){object3d.position.copy(this.position);object3d.quaternion.copy(this.quaternion);object3d.scale.copy(this.scale);object3d.updateMatrix()};ARjs.HitTesting.Result.prototype.applyPosition=function(object3d){object3d.position.copy(this.position);object3d.updateMatrix();return this};ARjs.HitTesting.Result.prototype.applyQuaternion=function(object3d){object3d.quaternion.copy(this.quaternion);object3d.updateMatrix();return this};var ARjs=ARjs||{};ARjs.Session=function(parameters){var _this=this;this.parameters={renderer:null,camera:null,scene:null,sourceParameters:{},contextParameters:{}};this.signals={sourceReady:new signals.Signal,contextInitialized:new signals.Signal};setParameters(parameters);function setParameters(parameters){if(parameters===undefined)return;for(var key in parameters){var newValue=parameters[key];if(newValue===undefined){console.warn("THREEx.Session: '"+key+"' parameter is undefined.");continue}var currentValue=_this.parameters[key];if(currentValue===undefined){console.warn("THREEx.Session: '"+key+"' is not a property of this material.");continue}_this.parameters[key]=newValue}}console.assert(this.parameters.renderer instanceof THREE.WebGLRenderer);console.assert(this.parameters.camera instanceof THREE.Camera);console.assert(this.parameters.scene instanceof THREE.Scene);Object.defineProperty(this,"renderer",{get:function(){console.warn("use .parameters.renderer renderer");return this.parameters.renderer}});Object.defineProperty(this,"camera",{get:function(){console.warn("use .parameters.camera instead");return this.parameters.camera}});Object.defineProperty(this,"scene",{get:function(){console.warn("use .parameters.scene instead");return this.parameters.scene}});console.log("AR.js",ARjs.Context.REVISION,"- trackingBackend:",parameters.contextParameters.trackingBackend);var arSource=_this.arSource=new ARjs.Source(parameters.sourceParameters);arSource.init(function onReady(){arSource.onResize(arContext,_this.parameters.renderer,_this.parameters.camera);_this.signals.sourceReady.dispatch()});window.addEventListener("resize",function(){arSource.onResize(arContext,_this.parameters.renderer,_this.parameters.camera)});var arContext=_this.arContext=new ARjs.Context(parameters.contextParameters);_this.arContext.init();arContext.addEventListener("initialized",function(event){arSource.onResize(arContext,_this.parameters.renderer,_this.parameters.camera);_this.signals.contextInitialized.dispatch()});this.update=function(){if(arSource.ready===false)return;arContext.update(arSource.domElement)}};ARjs.Session.prototype.onResize=function(){this.arSource.onResize(this.arContext,this.parameters.renderer,this.parameters.camera)};var ARjs=ARjs||{};ARjs.TangoPointCloud=function(arSession){var _this=this;var arContext=arSession.arContext;this.object3d=new THREE.Group;console.warn("Work only on cameraTransformMatrix - fix me - useless limitation");arContext.addEventListener("initialized",function(event){var vrPointCloud=arContext._tangoContext.vrPointCloud;var geometry=vrPointCloud.getBufferGeometry();var material=new THREE.PointsMaterial({size:.01,depthWrite:false});var pointsObject=new THREE.Points(geometry,material);pointsObject.frustumCulled=false;pointsObject.renderDepth=0;_this.object3d.add(pointsObject)})};var ARjs=ARjs||{};ARjs.TangoVideoMesh=function(arSession){var arContext=arSession.arContext;var renderer=arSession.renderer;var videoMesh=null;var vrDisplay=null;var sceneOrtho=new THREE.Scene;var cameraOrtho=new THREE.OrthographicCamera(-1,1,1,-1,0,100);this._sceneOrtho=sceneOrtho;this._cameraOrtho=cameraOrtho;arContext.addEventListener("initialized",function(event){console.assert(arContext.parameters.trackingBackend==="tango");vrDisplay=arContext._tangoContext.vrDisplay;console.assert(vrDisplay,"vrDisplay MUST be defined");if(vrDisplay.displayName!=="Tango VR Device")return;videoMesh=THREE.WebAR.createVRSeeThroughCameraMesh(vrDisplay);sceneOrtho.add(videoMesh)});this.update=function(){console.assert(arContext.parameters.trackingBackend==="tango");if(videoMesh===null)return;THREE.WebAR.updateCameraMeshOrientation(vrDisplay,videoMesh)};this.render=function(){console.assert(arContext.parameters.trackingBackend==="tango");renderer.render(sceneOrtho,cameraOrtho);renderer.clearDepth()}};var ARjs=ARjs||{};ARjs.Utils={};ARjs.Utils.createDefaultCamera=function(trackingMethod){var trackingBackend=this.parseTrackingMethod(trackingMethod).trackingBackend;if(trackingBackend==="artoolkit"){var camera=new THREE.Camera}else if(trackingBackend==="aruco"){var camera=new THREE.PerspectiveCamera(42,window.innerWidth/window.innerHeight,.01,100)}else if(trackingBackend==="tango"){var camera=new THREE.PerspectiveCamera(42,window.innerWidth/window.innerHeight,.01,100)}else console.assert(false,"unknown trackingBackend: "+trackingBackend);return camera};ARjs.Utils.isTango=function(){var isTango=navigator.userAgent.match("Chrome/57.0.2987.5")!==null?true:false;return isTango};ARjs.Utils.parseTrackingMethod=function(trackingMethod){if(trackingMethod==="best"){trackingMethod=ARjs.Utils.isTango()?"tango":"area-artoolkit"}if(trackingMethod.startsWith("area-")){return{trackingBackend:trackingMethod.replace("area-",""),markersAreaEnabled:true}}else{return{trackingBackend:trackingMethod,markersAreaEnabled:false}}};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkersAreaControls=THREEx.ArMultiMarkerControls=function(arToolkitContext,object3d,parameters){var _this=this;THREEx.ArBaseControls.call(this,object3d);if(arguments.length>3)console.assert("wrong api for",THREEx.ArMultiMarkerControls);this.parameters={subMarkersControls:parameters.subMarkersControls,subMarkerPoses:parameters.subMarkerPoses,changeMatrixMode:parameters.changeMatrixMode!==undefined?parameters.changeMatrixMode:"modelViewMatrix"};this.object3d.visible=false;this.subMarkersControls=this.parameters.subMarkersControls;this.subMarkerPoses=this.parameters.subMarkerPoses;arToolkitContext.addEventListener("sourceProcessed",function(){_this._onSourceProcessed()})};ARjs.MarkersAreaControls.prototype=Object.create(THREEx.ArBaseControls.prototype);ARjs.MarkersAreaControls.prototype.constructor=ARjs.MarkersAreaControls;ARjs.MarkersAreaControls.prototype._onSourceProcessed=function(){var _this=this;var stats={count:0,position:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)},quaternion:{sum:new THREE.Quaternion(0,0,0,0),average:new THREE.Quaternion(0,0,0,0)},scale:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)}};var firstQuaternion=_this.parameters.subMarkersControls[0].object3d.quaternion;this.parameters.subMarkersControls.forEach(function(markerControls,markerIndex){var markerObject3d=markerControls.object3d;if(markerObject3d.visible===false)return;var matrix=markerObject3d.matrix.clone();var markerPose=_this.parameters.subMarkerPoses[markerIndex];matrix.multiply((new THREE.Matrix4).getInverse(markerPose));var position=new THREE.Vector3;var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3;matrix.decompose(position,quaternion,scale);stats.count++;ARjs.MarkersAreaControls.averageVector3(stats.position.sum,position,stats.count,stats.position.average);ARjs.MarkersAreaControls.averageQuaternion(stats.quaternion.sum,quaternion,firstQuaternion,stats.count,stats.quaternion.average);ARjs.MarkersAreaControls.averageVector3(stats.scale.sum,scale,stats.count,stats.scale.average)});if(stats.count>0){_this.object3d.visible=true}else{_this.object3d.visible=false}if(stats.count>0){var modelViewMatrix=new THREE.Matrix4;modelViewMatrix.compose(stats.position.average,stats.quaternion.average,stats.scale.average);if(this.parameters.changeMatrixMode==="modelViewMatrix"){_this.object3d.matrix.copy(modelViewMatrix)}else if(this.parameters.changeMatrixMode==="cameraTransformMatrix"){_this.object3d.matrix.getInverse(modelViewMatrix)}else{console.assert(false)}_this.object3d.matrix.decompose(_this.object3d.position,_this.object3d.quaternion,_this.object3d.scale)}};ARjs.MarkersAreaControls.averageQuaternion=function(quaternionSum,newQuaternion,firstQuaternion,count,quaternionAverage){quaternionAverage=quaternionAverage||new THREE.Quaternion;console.assert(firstQuaternion instanceof THREE.Quaternion===true);if(newQuaternion.dot(firstQuaternion)>0){newQuaternion=new THREE.Quaternion(-newQuaternion.x,-newQuaternion.y,-newQuaternion.z,-newQuaternion.w)}quaternionSum.x+=newQuaternion.x;quaternionSum.y+=newQuaternion.y;quaternionSum.z+=newQuaternion.z;quaternionSum.w+=newQuaternion.w;quaternionAverage.x=quaternionSum.x/count;quaternionAverage.y=quaternionSum.y/count;quaternionAverage.z=quaternionSum.z/count;quaternionAverage.w=quaternionSum.w/count;quaternionAverage.normalize();return quaternionAverage};ARjs.MarkersAreaControls.averageVector3=function(vector3Sum,vector3,count,vector3Average){vector3Average=vector3Average||new THREE.Vector3;vector3Sum.x+=vector3.x;vector3Sum.y+=vector3.y;vector3Sum.z+=vector3.z;vector3Average.x=vector3Sum.x/count;vector3Average.y=vector3Sum.y/count;vector3Average.z=vector3Sum.z/count;return vector3Average};ARjs.MarkersAreaControls.computeCenter=function(jsonData){var multiMarkerFile=JSON.parse(jsonData);var stats={count:0,position:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)},quaternion:{sum:new THREE.Quaternion(0,0,0,0),average:new THREE.Quaternion(0,0,0,0)},scale:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)}};var firstQuaternion=new THREE.Quaternion;multiMarkerFile.subMarkersControls.forEach(function(item){var poseMatrix=(new THREE.Matrix4).fromArray(item.poseMatrix);var position=new THREE.Vector3;var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3;poseMatrix.decompose(position,quaternion,scale);stats.count++;ARjs.MarkersAreaControls.averageVector3(stats.position.sum,position,stats.count,stats.position.average);ARjs.MarkersAreaControls.averageQuaternion(stats.quaternion.sum,quaternion,firstQuaternion,stats.count,stats.quaternion.average);ARjs.MarkersAreaControls.averageVector3(stats.scale.sum,scale,stats.count,stats.scale.average)});var averageMatrix=new THREE.Matrix4;averageMatrix.compose(stats.position.average,stats.quaternion.average,stats.scale.average);return averageMatrix};ARjs.MarkersAreaControls.computeBoundingBox=function(jsonData){var multiMarkerFile=JSON.parse(jsonData);var boundingBox=new THREE.Box3;multiMarkerFile.subMarkersControls.forEach(function(item){var poseMatrix=(new THREE.Matrix4).fromArray(item.poseMatrix);var position=new THREE.Vector3;var quaternion=new THREE.Quaternion;var scale=new THREE.Vector3;poseMatrix.decompose(position,quaternion,scale);boundingBox.expandByPoint(position)});return boundingBox};ARjs.MarkersAreaControls.prototype.updateSmoothedControls=function(smoothedControls,lerpsValues){if(lerpsValues===undefined){lerpsValues=[[.3+.1,.1,.3],[.4+.1,.1,.4],[.4+.1,.2,.5],[.5+.1,.2,.7],[.5+.1,.2,.7]]}var nVisible=0;this.parameters.subMarkersControls.forEach(function(markerControls,markerIndex){var markerObject3d=markerControls.object3d;if(markerObject3d.visible===true)nVisible++});if(lerpsValues[nVisible-1]!==undefined){var lerpValues=lerpsValues[nVisible-1]}else{var lerpValues=lerpsValues[lerpsValues.length-1]}smoothedControls.parameters.lerpPosition=lerpValues[0];smoothedControls.parameters.lerpQuaternion=lerpValues[1];smoothedControls.parameters.lerpScale=lerpValues[2]};ARjs.MarkersAreaControls.fromJSON=function(arToolkitContext,parent3D,markerRoot,jsonData,parameters){var multiMarkerFile=JSON.parse(jsonData);var subMarkersControls=[];var subMarkerPoses=[];parameters=parameters||{};multiMarkerFile.subMarkersControls.forEach(function(item){var markerRoot=new THREE.Object3D;parent3D.add(markerRoot);var subMarkerControls=new THREEx.ArMarkerControls(arToolkitContext,markerRoot,item.parameters);subMarkersControls.push(subMarkerControls);subMarkerPoses.push((new THREE.Matrix4).fromArray(item.poseMatrix))});parameters.subMarkersControls=subMarkersControls;parameters.subMarkerPoses=subMarkerPoses;var multiMarkerControls=new THREEx.ArMultiMarkerControls(arToolkitContext,markerRoot,parameters);return multiMarkerControls};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkersAreaLearning=THREEx.ArMultiMakersLearning=function(arToolkitContext,subMarkersControls){var _this=this;this._arToolkitContext=arToolkitContext;this.subMarkersControls=subMarkersControls;this.enabled=true;arToolkitContext.addEventListener("sourceProcessed",function(){_this._onSourceProcessed()})};ARjs.MarkersAreaLearning.prototype._onSourceProcessed=function(){var originQuaternion=this.subMarkersControls[0].object3d.quaternion;if(this.enabled===false)return;var visibleMarkerControls=this.subMarkersControls.filter(function(markerControls){return markerControls.object3d.visible===true});var count=Object.keys(visibleMarkerControls).length;var positionDelta=new THREE.Vector3;var quaternionDelta=new THREE.Quaternion;var scaleDelta=new THREE.Vector3;var tmpMatrix=new THREE.Matrix4;for(var i=0;i<count;i++){var markerControls1=visibleMarkerControls[i];for(var j=0;j<count;j++){var markerControls2=visibleMarkerControls[j];if(i===j)continue;if(markerControls1.object3d.userData.seenCouples===undefined){markerControls1.object3d.userData.seenCouples={}}var seenCouples=markerControls1.object3d.userData.seenCouples;if(seenCouples[markerControls2.id]===undefined){seenCouples[markerControls2.id]={count:0,position:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)},quaternion:{sum:new THREE.Quaternion(0,0,0,0),average:new THREE.Quaternion(0,0,0,0)},scale:{sum:new THREE.Vector3(0,0,0),average:new THREE.Vector3(0,0,0)}}}tmpMatrix.getInverse(markerControls1.object3d.matrix);tmpMatrix.multiply(markerControls2.object3d.matrix);tmpMatrix.decompose(positionDelta,quaternionDelta,scaleDelta);var stats=seenCouples[markerControls2.id];stats.count++;THREEx.ArMultiMarkerControls.averageVector3(stats.position.sum,positionDelta,stats.count,stats.position.average);THREEx.ArMultiMarkerControls.averageQuaternion(stats.quaternion.sum,quaternionDelta,originQuaternion,stats.count,stats.quaternion.average);THREEx.ArMultiMarkerControls.averageVector3(stats.scale.sum,scaleDelta,stats.count,stats.scale.average)}}};ARjs.MarkersAreaLearning.prototype.computeResult=function(){var _this=this;var originSubControls=this.subMarkersControls[0];this.deleteResult();originSubControls.object3d.userData.result={averageMatrix:new THREE.Matrix4,confidenceFactor:1};do{var resultChanged=false;this.subMarkersControls.forEach(function(subMarkerControls){var result=subMarkerControls.object3d.userData.result;var isLearned=result!==undefined&&result.confidenceFactor>=1?true:false;if(isLearned===true)return;var otherSubControlsID=_this._getLearnedCoupleStats(subMarkerControls);if(otherSubControlsID===null){return}var otherSubControls=_this._getSubMarkerControlsByID(otherSubControlsID);var seenCoupleStats=subMarkerControls.object3d.userData.seenCouples[otherSubControlsID];var averageMatrix=new THREE.Matrix4;averageMatrix.compose(seenCoupleStats.position.average,seenCoupleStats.quaternion.average,seenCoupleStats.scale.average);var otherAverageMatrix=otherSubControls.object3d.userData.result.averageMatrix;var matrix=(new THREE.Matrix4).getInverse(otherAverageMatrix).multiply(averageMatrix);matrix=(new THREE.Matrix4).getInverse(matrix);console.assert(subMarkerControls.object3d.userData.result===undefined);subMarkerControls.object3d.userData.result={averageMatrix:matrix,confidenceFactor:1};resultChanged=true})}while(resultChanged===true)};ARjs.MarkersAreaLearning.prototype._getLearnedCoupleStats=function(subMarkerControls){if(subMarkerControls.object3d.userData.seenCouples===undefined)return null;var seenCouples=subMarkerControls.object3d.userData.seenCouples;var coupleControlsIDs=Object.keys(seenCouples).map(Number);for(var i=0;i<coupleControlsIDs.length;i++){var otherSubControlsID=coupleControlsIDs[i];var otherSubControls=this._getSubMarkerControlsByID(otherSubControlsID);var result=otherSubControls.object3d.userData.result;var isLearned=result!==undefined&&result.confidenceFactor>=1?true:false;if(isLearned===false)continue;return otherSubControlsID}return null};ARjs.MarkersAreaLearning.prototype._getSubMarkerControlsByID=function(controlsID){for(var i=0;i<this.subMarkersControls.length;i++){var subMarkerControls=this.subMarkersControls[i];if(subMarkerControls.id===controlsID){return subMarkerControls}}return null};ARjs.MarkersAreaLearning.prototype.toJSON=function(){this.computeResult();var data={meta:{createdBy:"Area Learning - AR.js "+THREEx.ArToolkitContext.REVISION,createdAt:(new Date).toJSON()},trackingBackend:this._arToolkitContext.parameters.trackingBackend,subMarkersControls:[]};var originSubControls=this.subMarkersControls[0];var originMatrixInverse=(new THREE.Matrix4).getInverse(originSubControls.object3d.matrix);this.subMarkersControls.forEach(function(subMarkerControls,index){if(subMarkerControls.object3d.userData.result===undefined)return;var poseMatrix=subMarkerControls.object3d.userData.result.averageMatrix;console.assert(poseMatrix instanceof THREE.Matrix4);var info={parameters:{},poseMatrix:poseMatrix.toArray()};if(subMarkerControls.parameters.type==="pattern"){info.parameters.type=subMarkerControls.parameters.type;info.parameters.patternUrl=subMarkerControls.parameters.patternUrl}else if(subMarkerControls.parameters.type==="barcode"){info.parameters.type=subMarkerControls.parameters.type;info.parameters.barcodeValue=subMarkerControls.parameters.barcodeValue}else console.assert(false);data.subMarkersControls.push(info)});var strJSON=JSON.stringify(data,null," ");var humanReadable=false;if(humanReadable===true){var tmp=JSON.parse(strJSON);tmp.subMarkersControls.forEach(function(markerControls){markerControls.poseMatrix=markerControls.poseMatrix.map(function(value){var roundingFactor=100;return Math.round(value*roundingFactor)/roundingFactor})});strJSON=JSON.stringify(tmp,null," ")}return strJSON};ARjs.MarkersAreaLearning.prototype.resetStats=function(){this.deleteResult();this.subMarkersControls.forEach(function(markerControls){delete markerControls.object3d.userData.seenCouples})};ARjs.MarkersAreaLearning.prototype.deleteResult=function(){this.subMarkersControls.forEach(function(markerControls){delete markerControls.object3d.userData.result})};var THREEx=THREEx||{};var ARjs=ARjs||{};var THREEx=THREEx||{};ARjs.MarkersAreaUtils=THREEx.ArMultiMarkerUtils={};ARjs.MarkersAreaUtils.navigateToLearnerPage=function(learnerBaseURL,trackingBackend){var learnerParameters={backURL:location.href,trackingBackend:trackingBackend,markersControlsParameters:ARjs.MarkersAreaUtils.createDefaultMarkersControlsParameters(trackingBackend)};location.href=learnerBaseURL+"?"+encodeURIComponent(JSON.stringify(learnerParameters))};ARjs.MarkersAreaUtils.storeDefaultMultiMarkerFile=function(trackingBackend){var file=ARjs.MarkersAreaUtils.createDefaultMultiMarkerFile(trackingBackend);localStorage.setItem("ARjsMultiMarkerFile",JSON.stringify(file))};ARjs.MarkersAreaUtils.createDefaultMultiMarkerFile=function(trackingBackend){console.assert(trackingBackend);if(trackingBackend===undefined)debugger;var link=document.createElement("a");link.href=ARjs.Context.baseURL;var absoluteBaseURL=link.href;var file={meta:{createdBy:"AR.js "+ARjs.Context.REVISION+" - Default Marker",createdAt:(new Date).toJSON()},trackingBackend:trackingBackend,subMarkersControls:[]};file.subMarkersControls[0]={parameters:{},poseMatrix:(new THREE.Matrix4).makeTranslation(0,0,0).toArray()};if(trackingBackend==="artoolkit"){file.subMarkersControls[0].parameters.type="pattern";file.subMarkersControls[0].parameters.patternUrl=absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-hiro.patt";
}else if(trackingBackend==="aruco"){file.subMarkersControls[0].parameters.type="barcode";file.subMarkersControls[0].parameters.barcodeValue=1001}else console.assert(false);return file};ARjs.MarkersAreaUtils.createDefaultMarkersControlsParameters=function(trackingBackend){var link=document.createElement("a");link.href=ARjs.Context.baseURL;var absoluteBaseURL=link.href;if(trackingBackend==="artoolkit"){var markersControlsParameters=[{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-hiro.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-kanji.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterA.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterB.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterC.patt"},{type:"pattern",patternUrl:absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterF.patt"}]}else if(trackingBackend==="aruco"){var markersControlsParameters=[{type:"barcode",barcodeValue:1001},{type:"barcode",barcodeValue:1002},{type:"barcode",barcodeValue:1003},{type:"barcode",barcodeValue:1004},{type:"barcode",barcodeValue:1005},{type:"barcode",barcodeValue:1006}]}else console.assert(false);return markersControlsParameters};ARjs.MarkersAreaUtils.storeMarkersAreaFileFromResolution=function(trackingBackend,resolutionW,resolutionH){var areaFile=this.buildMarkersAreaFileFromResolution(trackingBackend,resolutionW,resolutionH);localStorage.setItem("ARjsMultiMarkerFile",JSON.stringify(areaFile))};ARjs.MarkersAreaUtils.buildMarkersAreaFileFromResolution=function(trackingBackend,resolutionW,resolutionH){var file={meta:{createdBy:"AR.js - Augmented Website",createdAt:(new Date).toJSON()},trackingBackend:trackingBackend,subMarkersControls:[]};var whiteMargin=.1;if(resolutionW>resolutionH){var markerImageSize=.4*resolutionH}else if(resolutionW<resolutionH){var markerImageSize=.4*resolutionW}else if(resolutionW===resolutionH){var markerImageSize=.33*resolutionW}else console.assert(false);var actualMarkerSize=markerImageSize*(1-2*whiteMargin);var deltaX=(resolutionW-markerImageSize)/2/actualMarkerSize;var deltaZ=(resolutionH-markerImageSize)/2/actualMarkerSize;var subMarkerControls=buildSubMarkerControls("center",0,0);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("topleft",-deltaX,-deltaZ);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("topright",+deltaX,-deltaZ);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("bottomleft",-deltaX,+deltaZ);file.subMarkersControls.push(subMarkerControls);var subMarkerControls=buildSubMarkerControls("bottomright",+deltaX,+deltaZ);file.subMarkersControls.push(subMarkerControls);return file;function buildSubMarkerControls(layout,positionX,positionZ){console.log("buildSubMarkerControls",layout,positionX,positionZ);var subMarkersControls={parameters:{},poseMatrix:(new THREE.Matrix4).makeTranslation(positionX,0,positionZ).toArray()};if(trackingBackend==="artoolkit"){layout2MarkerParametersArtoolkit(subMarkersControls.parameters,layout)}else if(trackingBackend==="aruco"){layout2MarkerParametersAruco(subMarkersControls.parameters,layout)}else console.assert(false);return subMarkersControls}function layout2MarkerParametersArtoolkit(parameters,layout){var link=document.createElement("a");link.href=ARjs.Context.baseURL;var absoluteBaseURL=link.href;var layout2PatternUrl={center:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-hiro.patt"),topleft:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterA.patt"),topright:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterB.patt"),bottomleft:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterC.patt"),bottomright:convertRelativeUrlToAbsolute(absoluteBaseURL+"examples/marker-training/examples/pattern-files/pattern-letterF.patt")};console.assert(layout2PatternUrl[layout]!==undefined);parameters.type="pattern";parameters.patternUrl=layout2PatternUrl[layout];return;function convertRelativeUrlToAbsolute(relativeUrl){var tmpLink=document.createElement("a");tmpLink.href=relativeUrl;return tmpLink.href}}function layout2MarkerParametersAruco(parameters,layout){var layout2Barcode={center:1001,topleft:1002,topright:1003,bottomleft:1004,bottomright:1005};console.assert(layout2Barcode[layout]);parameters.type="barcode";parameters.barcodeValue=layout2Barcode[layout]}};var PortableARjs=function(canvasEl,options){options=options||{};options.debugUI=options.debugUI!==undefined?options.debugUI:false;options.renderThreejs=options.renderThreejs!==undefined?options.renderThreejs:false;this.options=options;var trackingMethod="area-artoolkit";var arjsProfile=(new ARjs.Profile).sourceWebcam().trackingMethod(trackingMethod).changeMatrixMode("cameraTransformMatrix").defaultMarker().checkIfValid();var threejsScene=new THREE.Scene;var threejsCamera=ARjs.Utils.createDefaultCamera(trackingMethod);threejsScene.add(threejsCamera);var threejsRenderer=new THREE.WebGLRenderer({antialias:true,alpha:true});threejsRenderer.setClearColor(new THREE.Color("lightgrey"),0);threejsRenderer.setSize(640,480);threejsRenderer.domElement.style.position="absolute";threejsRenderer.domElement.style.top="0px";threejsRenderer.domElement.style.left="0px";var arjsSession=new ARjs.Session({scene:threejsScene,renderer:threejsRenderer,camera:threejsCamera,sourceParameters:arjsProfile.sourceParameters,contextParameters:arjsProfile.contextParameters});var arjsAnchor=new ARjs.Anchor(arjsSession,arjsProfile.defaultMarkerParameters);this.cameraProjectionMatrix=[];this.cameraTransformMatrix=[];this.update=function(){arjsSession.update();arjsAnchor.update();arjsSession.arSource.copyElementSizeTo(canvasEl);this.cameraProjectionMatrix=threejsCamera.projectionMatrix.toArray();this.cameraTransformMatrix=threejsCamera.matrix.toArray()};if(this.options.debugUI===true){this._initOptionsDebugUI(arjsSession,arjsAnchor)}if(this.options.renderThreejs===true){this._initOptionRenderThreejs(treejsRenderer,threejsScene,threejsCamera,arjsAnchor)}};PortableARjs.prototype._initOptionsDebugUI=function(arjsSession,arjsAnchor){if(document.querySelector("#arjsDebugUIContainer")===null){var domElement=document.createElement("div");domElement.id="arjsDebugUIContainer";domElement.setAttribute("style","position: fixed; bottom: 10px; width:100%; text-align: center; z-index: 1;color: grey;");document.body.appendChild(domElement)}var sessionDebugUI=new ARjs.SessionDebugUI(arjsSession);document.querySelector("#arjsDebugUIContainer").appendChild(sessionDebugUI.domElement);var anchorDebugUI=new ARjs.AnchorDebugUI(arjsAnchor);document.querySelector("#arjsDebugUIContainer").appendChild(anchorDebugUI.domElement)};PortableARjs.prototype._initOptionRenderThreejs=function(renderer,scene,camera,arjsAnchor){var onRenderFcts=[];var arWorldRoot=arjsAnchor.object3d;var geometry=new THREE.CubeGeometry(1,1,1);var material=new THREE.MeshNormalMaterial({transparent:true,opacity:.5,side:THREE.DoubleSide});var mesh=new THREE.Mesh(geometry,material);mesh.position.y=geometry.parameters.height/2;arWorldRoot.add(mesh);var geometry=new THREE.TorusKnotGeometry(.3,.1,64,16);var material=new THREE.MeshNormalMaterial;var mesh=new THREE.Mesh(geometry,material);mesh.position.y=.5;arWorldRoot.add(mesh);onRenderFcts.push(function(delta){mesh.rotation.x+=Math.PI*delta});if(true){document.body.appendChild(renderer.domElement);onRenderFcts.push(function(){renderer.render(scene,camera)})}var lastTimeMsec=null;requestAnimationFrame(function animate(nowMsec){requestAnimationFrame(animate);lastTimeMsec=lastTimeMsec||nowMsec-1e3/60;var deltaMsec=Math.min(200,nowMsec-lastTimeMsec);lastTimeMsec=nowMsec;onRenderFcts.forEach(function(onRenderFct){onRenderFct(deltaMsec/1e3,nowMsec/1e3)})})};
three.js/src/threex/threex-artoolkitcontext.js
浏览文件 @
639d6889
...
...
@@ -76,7 +76,7 @@ Object.assign( ARjs.Context.prototype, THREE.EventDispatcher.prototype );
// ARjs.Context.baseURL = '../'
// default to github page
ARjs
.
Context
.
baseURL
=
'
https://jeromeetienne.github.io/AR.js/three.js/
'
ARjs
.
Context
.
REVISION
=
'
1.6.
1
'
ARjs
.
Context
.
REVISION
=
'
1.6.
2
'
...
...
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录