PanoBoxFrame.js 184 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057
  1. import * as THREE from 'three'
  2. import math from './util/math.js'
  3. import common from './util/common.js'
  4. import BoundingMesh from './util/BoundingMesh.js'
  5. import Vectors from './util/Vectors.js'
  6. const version = 'output'
  7. const convertTool = {
  8. getQuaByAim: function (aim, center=new THREE.Vector3, forward=new THREE.Vector3(0, 0, -1)){ //z朝上的坐标系是 forward = new THREE.Vector3(0, 1, 0)
  9. let qua1 = new THREE.Quaternion().setFromUnitVectors(forward, aim.clone().sub(center).normalize())
  10. //或var _ = (new THREE.Matrix4).lookAt(pano.position, aim, new THREE.Vector3(0,1,0)); aimQua = (new THREE.Quaternion).setFromRotationMatrix(_);
  11. return qua1
  12. },
  13. }
  14. //----------------------复制以下内容---------------------------------
  15. let player,
  16. skyBoxTight,
  17. meshGroup,
  18. modelBound = new THREE.Box3(),
  19. ray = new THREE.Raycaster(),
  20. groundPlane = new THREE.Plane()
  21. let groundY, safeBound, boundConfirmed //安全区域应该在扣除每种类型柜子大概的长宽的一半
  22. let hue = 0,
  23. startTime
  24. const MinBoxInitialScore = 0.68 //找不到匹配时,若box分数低于该值,不createSinglePano
  25. let boxesSolid = []
  26. let standards = {
  27. cabinet: {
  28. widthNormal: { min: 0.55, max: 0.65 }, //widthNormal是不计宽还是厚度的平均宽度 //个别场景如S9yepREK8Jl 宽0.8米
  29. height: { min: 0.3, max: 2.5, standard: 2 },
  30. closeRatio: 0.7, //数值越小越容易findRest。一般在墙上的位置不准要设置大些,扎堆放置的设置小些
  31. },
  32. fire: {
  33. widthNormal: { min: 0.12, max: 0.16 },
  34. height: { min: 0.4, max: 0.58 },
  35. widthSame: true, //长宽相等
  36. closeRatio: 4,
  37. tinyXZ: true, //可以通过它近似确定地面高度
  38. },
  39. air: {
  40. widthNormal: { min: 0.35, max: 0.7 },
  41. width: { min: 0.48, max: 0.75 }, //因为总是斜着放所以范围较大
  42. thick: { min: 0.33, max: 0.5 },
  43. height: { min: 1.2, max: 2.2, standard: 1.8 },
  44. atWall: 0.8,
  45. closeRatio: 1.1,
  46. },
  47. airSmart: {
  48. widthNormal: { min: 0.35, max: 0.7 },
  49. width: { min: 0.48, max: 0.75 }, //因为总是斜着放所以范围较大
  50. thick: { min: 0.33, max: 0.5 },
  51. height: { min: 1.2, max: 2.2, standard: 1.8 },
  52. atWall: 0.8,
  53. closeRatio: 1.1,
  54. },
  55. 'air-hanging': {
  56. widthNormal: { min: 0.3, max: 1 },
  57. width: { min: 0.8, max: 1.1 },
  58. thick: { min: 0.2, max: 0.3 },
  59. height: { min: 0.3, max: 0.5, standard: 0.4 }, //standard是通常出现的最高高度. 有这个值的在离地的时候直接使用该高度
  60. bottom: { min: 0.8, max: 2.0 }, // 不绝对,大部分
  61. atWall: 1, //在墙壁的可能性
  62. closeRatio: 1.5,
  63. },
  64. battery: {
  65. widthNormal: { min: 0.45, max: 1.35 },
  66. width: { min: 0.7, max: 1.4 },
  67. thick: { min: 0.35, max: 0.5 },
  68. height: { min: 0.3, max: 2.5 }, //maxHeight
  69. //有的电池很小。考虑是否追加battery-little 并且限制大电池的长宽高比例
  70. atWall: 0.9,
  71. closeRatio: 0.9,
  72. },
  73. groundBar: {
  74. widthNormal: { min: 0.06, max: 0.4 },
  75. width: { min: 0.3, max: 0.5 },
  76. thick: { min: 0.05, max: 0.08 },
  77. height: { min: 0.1, max: 0.2 },
  78. bottom: { min: 1.2, max: 3 },
  79. atWall: 1,
  80. closeRatio: 2,
  81. },
  82. hlkcWindow: {
  83. widthNormal: { min: 0.08, max: 0.5 },
  84. width: { min: 0.35, max: 0.5 },
  85. thick: { min: 0.03, max: 0.06 },
  86. height: { min: 0.35, max: 0.5 },
  87. bottom: { min: 1.2, max: 3 },
  88. atWall: 1,
  89. closeRatio: 2,
  90. },
  91. electric: {
  92. widthNormal: { min: 0.2, max: 0.7 },
  93. width: { min: 0.5, max: 0.65 },
  94. thick: { min: 0.2, max: 0.3 },
  95. height: { min: 0.5, max: 1 }, //maxHeight 4GqaqNdyjGf一米高
  96. bottom: { min: 0.8, max: 1.8 },
  97. atWall: 1,
  98. closeRatio: 2,
  99. },
  100. monitor: {
  101. widthNormal: { min: 0.08, max: 0.11 },
  102. height: { min: 0.1, max: 0.2, standard: 0.15 }, //maxHeight
  103. bottom: { min: 1.2, max: 3 },
  104. atWall: 1,
  105. closeRatio: 4,
  106. tiny: true, //因为较小且无方向,所以近似一个点,用射线算出的位置比墙面还准,所以其最终位置可用于expandModelBound
  107. },
  108. rowBigBox: {
  109. widthNormal: { min: 0.55, max: Infinity },
  110. height: { min: 0.7, max: 2.4, standard: 2 },
  111. },
  112. /*"cabling-wall":{
  113. },
  114. "cabling-ceil":{
  115. atCeil:1
  116. } */
  117. }
  118. /* const typeNames = {
  119. cabinet : 'cabinet', //标准机柜
  120. air : 'air', //普通空调柜式
  121. battery : 'battery', //蓄电池组
  122. }
  123. */
  124. const typeNames = {
  125. fire: 'extinguisher', //灭火器
  126. monitor: 'surveillance_camera', //监控摄像机 放第一个,用于继续确定边界
  127. hlkcWindow: 'hlkc', //馈线窗
  128. groundBar: 'grounding_bar', //接地排
  129. cabinet: 'equipment_cabinet', //标准机柜
  130. battery: 'accumulator', //蓄电池组
  131. /* ac : 'ac_switchboard', //交流配电柜 //这两种合并,因为差别太小了,见QlJau21WP8G的,在全景图两侧识别的竟然一个ac一个dc
  132. dc : 'dc_distribution', //直流配电设备 */
  133. electric: ['ac_switchboard', 'dc_distribution'],
  134. air: 'sdkt', //普通空调柜式
  135. airSmart: 'ventilation_installation', //智能通风设备
  136. //cabling : 'cabling_rack', //单层走线架 因为在天花板的走线有点复杂,经常断开,无法确定方向所以放弃
  137. }
  138. /* const typeNamesReverse = {} //为了方便访问
  139. for(let i in typeNames){
  140. typeNamesReverse[typeNames[i]] = i
  141. }
  142. */
  143. let addLine = (origin, dir, len, color) => {
  144. if (version != 'vision') return
  145. var line1 = LineDraw.createLine([origin, origin.clone().add(dir.clone().multiplyScalar(len || 1))], { color })
  146. //console.log(origin.toArray(), dir.toArray())
  147. meshGroup.add(line1)
  148. return line1
  149. }
  150. let addLabel = (pos, text, { bgcolor, a } = {}) => {
  151. if (version != 'vision') return
  152. let shift = new THREE.Vector3(0, -0.2, 0)
  153. bgcolor = bgcolor ? new THREE.Color(bgcolor) : { r: 1, g: 1, b: 1 }
  154. //let endPos = new THREE.Vector3().addVectors(pos,shift);
  155. text instanceof Array || (text = [text])
  156. let lineCount = Math.round(Math.random() * 6) + 1
  157. let lines = []
  158. while (lineCount-- > 0) {
  159. lines.push('|')
  160. }
  161. text = [...text, ...lines, 'o']
  162. let textMesh = new TextSprite({
  163. text,
  164. textColor: { r: 0, g: 0, b: 0, a: 1 },
  165. backgroundColor: { r: bgcolor.r * 255, g: bgcolor.g * 255, b: bgcolor.b * 250, a: a || 0 },
  166. textBorderColor: { r: bgcolor.r * 255, g: bgcolor.g * 255, b: bgcolor.b * 250, a: a || 0.9 },
  167. textBorderThick: 2,
  168. margin: { x: 0, y: 0 },
  169. borderRadius: 0,
  170. player: player,
  171. sizeInfo: { minSize: 90, maxSize: 300, nearBound: 1, farBound: 7 },
  172. })
  173. textMesh.position.copy(pos)
  174. //textMesh.scale.set(0.3, 0.3, 0.3)
  175. meshGroup.add(textMesh)
  176. textMesh.sprite.position.y += textMesh.sprite.scale.y * 0.4
  177. return textMesh
  178. }
  179. let getBoxFinalPos = info => {
  180. //创建solidbox时的position
  181. let position
  182. let center = getBoxPos(info)
  183. if (standards[info.boxType].bottom) {
  184. //悬挂
  185. position = center
  186. } else {
  187. position = center.clone().setY(groundY + info.size.y / 2) //使着地
  188. }
  189. return position
  190. }
  191. const axises = [
  192. new THREE.Vector3(-1, 1, -1),
  193. new THREE.Vector3(1, 1, -1),
  194. new THREE.Vector3(1, 1, 1),
  195. new THREE.Vector3(-1, 1, 1),
  196. new THREE.Vector3(-1, -1, -1),
  197. new THREE.Vector3(1, -1, -1),
  198. new THREE.Vector3(1, -1, 1),
  199. new THREE.Vector3(-1, -1, 1),
  200. ]
  201. let traverse = (info, fun) => {
  202. //忽略.infos的row 的信息
  203. fun(info)
  204. info.list && info.list.forEach(a => traverse(a, fun))
  205. info.mixedFrom && info.mixedFrom.forEach(a => traverse(a, fun))
  206. }
  207. class Box {
  208. //结果
  209. constructor(info) {
  210. //preDealBox(info)
  211. this.setFromInfo(info)
  212. this.name = this.boxType + '-' + this.name
  213. if (version == 'vision' && boundConfirmed) this.draw()
  214. boxesSolid.push(this)
  215. }
  216. setFromInfo(info) {
  217. for (let i in info) {
  218. this[i] = info[i]
  219. }
  220. /* let h = info.size.y
  221. let standardH = standards[info.boxType].height.standard
  222. if (h > standardH) {
  223. h = standardH + Math.log(1 + (h - standardH) / 2) //Math.log2: 以2为底的对数 ,Math.log:自然对数
  224. info.size.y = h
  225. } */
  226. this.position = getBoxFinalPos(this)
  227. let bound = new THREE.Box3().setFromCenterAndSize(this.position, this.size)
  228. this.bound = bound
  229. }
  230. draw() {
  231. hue += 0.23
  232. var color = new THREE.Color().setHSL(hue, 0.9, 0.85)
  233. this.boxHelper = new THREE.Box3Helper(this.bound, color)
  234. this.boxHelper.material.depthTest = false
  235. this.boxHelper.material.transparent = true
  236. this.boxHelper.renderOrder = 30
  237. /* let { warnStr, exStr } = this
  238. warnStr && (exStr += `【${warnStr}】`) */
  239. this.label = addLabel(this.position, /* exStr ? [this.name, exStr] : */ this.score ? [this.name, this.score.toFixed(1)] : this.name, { bgcolor: color })
  240. meshGroup.add(this.boxHelper)
  241. }
  242. dispose() {
  243. let index = boxesSolid.indexOf(this)
  244. if (index > -1) {
  245. boxesSolid.splice(index, 1)
  246. if (version == 'vision' && boundConfirmed) {
  247. this.label.sprite.material.opacity = 0.3
  248. this.boxHelper.material.opacity = 0.2
  249. }
  250. }
  251. }
  252. traversePair(fun) {
  253. traverse(this, fun)
  254. }
  255. getDirection(){//获得正面朝向。 需要全部box都创建完再调用
  256. let xProp = this.xProp
  257. let dir
  258. //哪边pano多朝哪边
  259. if(this.boxType == 'cabinet' && this.name.includes('row')){
  260. if(this.infos.box.length>1){
  261. let k = this.infos.reduce((w,c)=>{return w+c.k},0)
  262. xProp = k>1 ? 'width' : 'thick'
  263. }else{ //直接使用别的多box的row的方向 ,大多数都相同(会有例外,无所谓了)
  264. let rows = boxesSolid.filter(e=>e.boxType == 'cabinet' && e.name.includes('row'))
  265. rows.sort((a,b)=>b.infos.box.length - a.infos.box.length)
  266. let box = rows[0]
  267. if(box){
  268. return this.dirQua = box.dirQua
  269. }
  270. }
  271. }
  272. if(!xProp){//根据房间的长宽 散落的cabinet。 fire monitor
  273. let {xWidthPossible, yWidthPossible} = getBoxDirProp(this,true)
  274. xProp = this.xProp
  275. /* if(Math.abs(xWidthPossible - yWidthPossible) < 0.3){
  276. let size = new THREE.Vector3()
  277. safeBound.getSize(size)
  278. xWidthPossible += (size.x - size.z) * 0.5
  279. if(xWidthPossible > yWidthPossible){
  280. xProp = 'width'
  281. }
  282. } */
  283. }
  284. if(xProp){
  285. if(!this.panosDir) getPanosDir(this)
  286. if(xProp == 'width'){
  287. if (Math.abs(this.panosDir['z+']) < Math.abs(this.panosDir['z-'])) {//朝-z//也就是新坐标系的y
  288. //this.dirQua='下'
  289. dir = new THREE.Vector3(0,1,0)
  290. }else{//朝+z
  291. //this.dirQua='上'
  292. dir = new THREE.Vector3(0,-1,0)
  293. }
  294. }else{
  295. if (Math.abs(this.panosDir['x+']) < Math.abs(this.panosDir['x-'])) {//朝-x
  296. //this.dirQua='右'
  297. dir = new THREE.Vector3(-1,0,0)
  298. }else{//朝+x
  299. //this.dirQua='左'
  300. dir = new THREE.Vector3(1,0,0)
  301. }
  302. }
  303. }
  304. //addLabel(this.position, this.dirQua)
  305. this.dirQua = convertTool.getQuaByAim(dir, new THREE.Vector3, new THREE.Vector3(0,1,0))
  306. return this.dirQua
  307. /*飞到俯视图查看(不旋转视图,x朝右,z朝下)。以下四个qua是四个墙壁每个墙壁上的dirQua。
  308. _x: 0, _y: -0, _z: 1, _w: 0
  309. _x: 0, _y: 0, _z: -0.707, _w: 0.707 _x: 0, _y: -0, _z: 0.707, _w: 0.707
  310. x: 0, _y: 0, _z: 0, _w: 1
  311. */
  312. }
  313. toJson() {//转出的坐标系是z朝上的
  314. let category = typeNames[this.boxType]
  315. if (category instanceof Array) {
  316. let scoreMap = new Map()
  317. category = category.slice(0)
  318. category.forEach(e => scoreMap.set(e, 0)) //初始化
  319. //判断boxType: 寻找所使用的box总分最高的boxType
  320. let add = box => {
  321. if (!box) return
  322. let score = scoreMap.get(box.category) + box.score
  323. scoreMap.set(box.category, score)
  324. }
  325. this.traversePair(e => {
  326. add(e.box0)
  327. add(e.box1)
  328. })
  329. category = category.sort((a, b) => {
  330. return scoreMap.get(b) - scoreMap.get(a)
  331. })
  332. category = category[0] //最高分
  333. }
  334. this.getDirection()
  335. let json = {
  336. points: axises.map(axis => math.invertVisionVector(new THREE.Vector3().addVectors(this.position, this.size.clone().multiply(axis).multiplyScalar(0.5))).toArray()),
  337. category,
  338. type: this.boxType,
  339. sid: this.name,
  340. quaternion:this.dirQua.toArray()
  341. }
  342. return json
  343. }
  344. }
  345. // 2d坐标转3d坐标
  346. let getDirByUV = (uv, pano) => {
  347. // 计算方向向量
  348. let yaw = -uv.x * (Math.PI * 2)
  349. let pitch = Math.PI / 2 - uv.y * Math.PI
  350. let dir = new THREE.Vector3()
  351. dir.copy(Vectors.RIGHT).applyAxisAngle(Vectors.BACK, pitch).applyAxisAngle(Vectors.UP, yaw).applyQuaternion(pano.quaternion)
  352. return dir
  353. }
  354. let getCenterDir = box => {
  355. if (box.centerDir) return
  356. //假设不存在在box中间拍摄的情况,所以y不会横跨两边
  357. let bbox = box.bbox2
  358. let center = { x: getBbox2center(bbox[0], bbox[2]), y: (bbox[1] + bbox[3]) / 2 }
  359. box.bbox2CenterX = center.x
  360. let dir = getDirByUV(center, box.pano)
  361. box.centerDir = dir
  362. let centerTop = { x: center.x, y: bbox[1] }
  363. box.centerTopDir = getDirByUV(centerTop, box.pano)
  364. let centerBtm = { x: center.x, y: bbox[3] }
  365. box.centerBtmDir = getDirByUV(centerBtm, box.pano)
  366. let leftBtm = { x: bbox[0], y: bbox[3] }
  367. box.leftBtmDir = getDirByUV(leftBtm, box.pano)
  368. let rightBtm = { x: bbox[2], y: bbox[3] }
  369. box.rightBtmDir = getDirByUV(rightBtm, box.pano)
  370. }
  371. let getOtherPos = box => {
  372. if (!box.boxType) return
  373. let config = standards[box.boxType]
  374. if (!boundConfirmed) {
  375. if (!config.bottom) {
  376. ray.set(box.pano.position, box.centerBtmDir)
  377. box.btmPosPredict = ray.ray.intersectPlane(groundPlane, new THREE.Vector3()) //没有的话就在空中 (部分air-hanging也会有)。 fire的这个值会较大误差,因为groundY还不确定,但不影响,因只用它射线交点的位置。
  378. if (box.btmPosPredict) {
  379. let dir2d = new THREE.Vector2(box.centerBtmDir.x, box.centerBtmDir.z).normalize()
  380. let { min, max } = standards[box.boxType].widthNormal
  381. min = min * 0.4
  382. max = max * 0.4
  383. let minA = Math.min(Math.abs(dir2d.x), Math.abs(dir2d.y))
  384. const depth = math.linearClamp(minA, 0, 1, min, max)
  385. /* const depth = box.category == typeNames.cabinet ? 0.5 : 0.4
  386. */
  387. dir2d = dir2d.clone().multiplyScalar(depth)
  388. box.btmPosPredict.x += dir2d.x
  389. box.btmPosPredict.z += dir2d.y
  390. //addLabel(box.btmPosPredict,'b_'+box.category+"_"+box.sid, {bgcolor:'#6ff',a:0.1})
  391. //box.btmPosPredict.clamp(safeBound.min, safeBound.max)
  392. }
  393. }
  394. return
  395. }
  396. if (!box.posAtWall && config.atWall > 0) {
  397. //console.log(box.sid, 'getPosWall')
  398. const shrink = config.thick ? config.thick.min : config.widthNormal.min
  399. ray.set(box.pano.position, box.centerDir)
  400. let o = ray.intersectObjects([skyBoxTight])
  401. if (o[0]) box.posAtWall = new THREE.Vector3().addVectors(box.pano.position, box.centerDir.clone().multiplyScalar(o[0].distance - shrink))
  402. //因墙壁不准确,所以还是尽量不用墙的位置
  403. /* if(box.btmPos){
  404. let wallRatio = 0.5;
  405. if(new THREE.Vector3().subVectors(box.btmPos, box.posAtWall).setY(0).length() > 1 )wallRatio = 0.2 //可能墙壁位置不准,靠后了
  406. box.predictCenter = new THREE.Vector3().addVectors(box.btmPos.clone().multiplyScalar(1-wallRatio), box.posAtWall.clone().multiplyScalar(wallRatio))
  407. //box.predictCenter = new THREE.Vector3().addVectors(box.posAtWall, box.btmPos).multiplyScalar(0.5) //也许能当中心点? 虽然y会低一些
  408. addLabel(box.predictCenter, box.sid+'-preC')
  409. } */
  410. }
  411. if (!box.btmPos) {
  412. getBoxBtm(box)
  413. }
  414. if (!box.topPos) {
  415. getBoxTop(box)
  416. }
  417. }
  418. let getUVs = box => {
  419. if (box.bbox2) return
  420. let uvs = []
  421. box.bbox2 = box.bbox.map((e, i) => {
  422. return i % 2 == 0 ? e / 4096 /* + 0.25 */ : e / 2048
  423. })
  424. }
  425. let getBoxBase = box => {
  426. getBoxType(box)
  427. getUVs(box)
  428. getCenterDir(box)
  429. getOtherPos(box)
  430. }
  431. let getBbox2Diff = (x1, x2) => {
  432. //获取x1-x2,如果x1在x2右边则为正
  433. if (Math.abs(x1 - x2) < 0.5) return x1 - x2
  434. else {
  435. if (x1 > x2) x1 -= 1
  436. else x2 -= 1
  437. return x1 - x2
  438. }
  439. }
  440. let getBbox2center = (x1, x2) => {
  441. //找中间位置
  442. if (Math.abs(x1 - x2) > 0.5) {
  443. //永远找小于180度的那一边
  444. return (x1 + x2 + 1) / 2 //另外半边
  445. } else {
  446. return (x1 + x2) / 2
  447. }
  448. }
  449. let getBoxTop = info => {
  450. /* if(info.sid == 'pano0-11(mix4,8)'){
  451. console.log(5)
  452. } */
  453. if (info.box1) {
  454. let o2 = getIntersect2(info.box0.pano.position, info.box0.centerTopDir, info.box1.pano.position, info.box1.centerTopDir)
  455. info.topPos = o2.pos3d
  456. info.diffHeight = o2.mid2 ? o2.mid2.distanceTo(o2.mid1) : 1
  457. if (info.box0.topPos && info.box1.topPos) {
  458. info.topPos.y = (info.box0.topPos.y + info.box1.topPos.y) / 2 //原先的不准
  459. }
  460. } else {
  461. //取btm上方对应的位置 ( 因为和skybox的交点会因离墙远而偏上或偏下)
  462. let box = info.box0 || info
  463. let btm = box.btmPos
  464. if (!btm) {
  465. btm = getBoxBtm(info)
  466. }
  467. box.topPos = btm.clone() //xz同btm,要求y
  468. let xDelta = btm.x - box.pano.position.x
  469. let zDelta = btm.z - box.pano.position.z
  470. let yDelta
  471. //因为pano有旋转所以btm和top的xz其实是不一样的,所以会有误差。 故这里选择delta较大的
  472. if (Math.abs(xDelta) < Math.abs(zDelta)) {
  473. yDelta = (zDelta * box.centerTopDir.y) / box.centerTopDir.z
  474. /* console.log('use z', box)
  475. if(Math.abs(xDelta)<0.1)console.error('!!!!!!!!!!!!!!!!!!!!!!! xDelta',xDelta, box.sid ) */
  476. } else {
  477. yDelta = (xDelta * box.centerTopDir.y) / box.centerTopDir.x
  478. // console.log('use x', box)
  479. }
  480. box.topPos.y = yDelta + box.pano.position.y
  481. let minHeight = /* info.boxType ? standards[info.boxType].height.min : box.category == typeNames.air ? 0.5 : */ standards[getBoxType(box)].height.min
  482. let diffH = Math.max(box.topPos.y - btm.y, minHeight)
  483. box.topPos.y = btm.y + diffH
  484. info.topPos = box.topPos
  485. /* if (box.sid == 'pano2-1') {
  486. addLabel(box.topPos,'t_'+box.sid,{bgcolor:'#ff4399'})
  487. addLine(box.pano.position,box.centerTopDir, 20)
  488. } */
  489. }
  490. return info.topPos
  491. }
  492. let getBoxBtm = info => {
  493. if (info.box1) {
  494. let o2 = getIntersect2(info.box0.pano.position, info.box0.centerBtmDir, info.box1.pano.position, info.box1.centerBtmDir)
  495. info.btmPos = o2.pos3d
  496. //info.btmPos.y = (info.box0.btmPos.y + info.box1.btmPos.y)/2 //原先的不准
  497. } else {
  498. let box = info.box0 || info
  499. if (!box.btmPos) {
  500. if (box.sid == 'pano0-7') {
  501. console.log(3)
  502. addLine(box.pano.position, box.centerBtmDir, 20)
  503. }
  504. if (!boundConfirmed) {
  505. return box.btmPosPredict
  506. }
  507. ray.set(box.pano.position, box.centerBtmDir)
  508. let o = ray.intersectObjects([skyBoxTight]) //如果skybound有问题,位置就会错
  509. box.btmPosOri = o[0].point.clone()
  510. let depth //缩进 //let depth = Math.abs(o[0].face.normal.y) > 0.9 ? 0.4 : -0.4
  511. getBoxType(box)
  512. let dir2d = new THREE.Vector2(box.centerBtmDir.x, box.centerBtmDir.z).normalize()
  513. if (standards[box.boxType].thick && standards[box.boxType].atWall /* box.boxType == 'battery' */) {
  514. //平贴于墙上,且厚度和宽度相差较大
  515. //注:air-hanging主要用的是posAtWall
  516. let { min, max } = standards[box.boxType].widthNormal
  517. min = min * 0.3
  518. max = max * 0.5
  519. if (!box.xProp) getBoxDirProp(box)
  520. if (box.xProp == 'width') {
  521. depth = math.linearClamp(Math.abs(dir2d.x), 0, 1, min, max)
  522. } else {
  523. depth = math.linearClamp(Math.abs(dir2d.y), 0, 1, min, max)
  524. }
  525. } else {
  526. let w = standards[box.boxType].thick || standards[box.boxType].widthNormal
  527. let w0 = (w.min + w.max) / 2
  528. let min = w0 * 0.5,
  529. max = w0 * 0.8
  530. let minA = Math.min(Math.abs(box.centerBtmDir.x), Math.abs(box.centerBtmDir.z))
  531. depth = math.linearClamp(minA, 0, 0.707, min /* 0.3 */, max /* 0.5 */) //在45度时需要最长的距离。主要针对cabinet
  532. }
  533. if (Math.abs(o[0].face.normal.y) < 0.9) {
  534. if (standards[box.boxType].atWall || o[0].point.y - groundY > 0.3) {
  535. //battery的识别框比较乱,有可能一个电池被识别出好几个,所以
  536. depth *= -1 //at wall
  537. }
  538. }
  539. let dir2d1 = dir2d.clone().multiplyScalar(depth)
  540. box.btmPos = o[0].point.clone()
  541. box.btmPos.x += dir2d1.x
  542. box.btmPos.z += dir2d1.y
  543. //addLabel(box.btmPos,'b_'+box.sid,{bgcolor:'#ff4399'})
  544. }
  545. info.btmPos = box.btmPos
  546. }
  547. return info.btmPos
  548. }
  549. let getIntersect = (pano0Pos, dir0, pano1Pos, dir1) => {
  550. let pos0 = new THREE.Vector3().addVectors(pano0Pos, dir0)
  551. let pos1 = new THREE.Vector3().addVectors(pano1Pos, dir1)
  552. /* var {pos3d, mid1, mid2, behind} = math.getLineIntersect({ A: pano0Pos.clone(), B: pano1Pos.clone(), p1: pos0, p2: pos1 })
  553. */ //三维线若接近平行,算出的交点可能很近,不是实际应该无交点才对
  554. var pos2d = math.isLineIntersect(
  555. [
  556. { x: pano0Pos.x, y: pano0Pos.z },
  557. { x: pos0.x, y: pos0.z },
  558. ],
  559. [
  560. { x: pano1Pos.x, y: pano1Pos.z },
  561. { x: pos1.x, y: pos1.z },
  562. ],
  563. true
  564. ) //优先考虑水平面方向的交点
  565. if (pos2d) {
  566. let y0 = ((pos2d.x - pano0Pos.x) * dir0.y) / dir0.x + pano0Pos.y
  567. let y1 = ((pos2d.x - pano1Pos.x) * dir1.y) / dir1.x + pano1Pos.y
  568. //console.log(y1-y0)
  569. let pos3d = new THREE.Vector3(pos2d.x, (y0 + y1) / 2, pos2d.y)
  570. return { pos3d, diffHeight: Math.abs(y0 - y1) } //diffHeight越小越好
  571. }
  572. }
  573. //究竟哪个比较准 - - 可能两个都判断?
  574. let getIntersect2 = (pano0Pos, dir0, pano1Pos, dir1) => {
  575. let pos0 = new THREE.Vector3().addVectors(pano0Pos, dir0)
  576. let pos1 = new THREE.Vector3().addVectors(pano1Pos, dir1)
  577. let o = math.getLineIntersect2({ A: pano0Pos.clone(), B: pano1Pos.clone(), p1: pos0, p2: pos1, dir0, dir1 }) //不用getLineIntersect,因为这个针对热点写的,当无交点时选用的点不是想要的
  578. if (!o.pos3d) {
  579. console.error('getIntersect2 no result? ?')
  580. }
  581. return o
  582. }
  583. let getBoxPos = info => {
  584. let boxType = getBoxType(info)
  585. return (
  586. (info.preDealRes && info.preDealRes.position) ||
  587. info.center ||
  588. (boxType && (standards[boxType].atWall > 0.5 && standards[boxType].bottom ? info.posAtWall : info.btmPos || info.btmPosPredict)) ||
  589. info.posAtWall
  590. )
  591. }
  592. let isType = (box, type) => {
  593. return typeNames[type] instanceof Array ? typeNames[type].includes(box.category) : typeNames[type] == box.category
  594. }
  595. let getBoxType = info => {
  596. if (info.boxType) return info.boxType
  597. let category = info.category || info.box0.category
  598. if (category == 'rowBigBox') info.boxType = 'rowBigBox'
  599. else {
  600. let type
  601. if (category == 'ac_switchboard') {
  602. console.log(1)
  603. }
  604. for (let i in typeNames) {
  605. if (typeNames[i] instanceof Array ? typeNames[i].includes(category) : typeNames[i] == category) {
  606. type = i
  607. break //type = typeNamesReverse[type]
  608. }
  609. }
  610. /* if(type == 'ac' || type == 'dc'){
  611. type = 'electric' //合并
  612. } */
  613. info.boxType = type
  614. }
  615. return info.boxType
  616. }
  617. /* let getBoxType = info => {
  618. let type = info.category || info.box0.category
  619. if (type == 'air') {
  620. let btm = info.btmPos || info.btmPos //btmPosAtWall
  621. if (!btm) {
  622. btm = getBoxBtm(info)
  623. }
  624. if (!btm) return
  625. let center = info.posAtWall || (info.preDealRes && info.preDealRes.position) || info.center
  626. const s = standards['air-hanging']
  627. if (btm.y - groundY > s.bottom.min) {
  628. let h0 = btm.y - groundY
  629. let h1 = (modelBound.max.y - center.y) / (modelBound.max.y - modelBound.min.y)
  630. let h2 = center.y - btm.y
  631. let score = h0 * 2 - h1 * 3 - h2 * 3
  632. if (score > 0) {
  633. type = 'air-hanging'
  634. }
  635. //console.error( score, h0,h1,h2, info.sid||info.name)
  636. } //注意:如果air被遮住底部,露出的部分只有一点,还是有可能被识别成air-hanging。只能希望
  637. //console.error( type, info.sid||info.name)
  638. }
  639. if (info.box0) {
  640. info.boxType = type
  641. //info.box1 && (info.box1.type = type) //因为box0和box1不一定匹配,所以不能直接赋值
  642. } else {
  643. info.type = type
  644. }
  645. } */
  646. let getPanosDir = (info, center) =>{
  647. center = center || getBoxPos(info)
  648. let dirs = { 'x+': 0, 'x-': 0, 'z+': 0, 'z-': 0, got: false }
  649. let getDirs = () => {
  650. //靠墙的在它到墙之间是不会有漫游点的
  651. if (dirs.got || !center) return
  652. player.model.panos.list.forEach(pano => {
  653. let dir = new THREE.Vector3().subVectors(pano.position, center)
  654. if (dir.x > 0) {
  655. dirs['x+'] += dir.x
  656. } else {
  657. dirs['x-'] += dir.x
  658. }
  659. if (dir.z > 0) {
  660. dirs['z+'] += dir.z
  661. } else {
  662. dirs['z-'] += dir.z
  663. }
  664. })
  665. dirs.got = true
  666. }
  667. getDirs()
  668. if(info.panosDir){
  669. console.error('already has dir')
  670. }
  671. info.panosDir = dirs
  672. return dirs
  673. }
  674. let getBoxDirProp = (info, force) => {
  675. //仅适用于方形单个房间房间,不可以是多边形、两个房间
  676. let xProp, yProp
  677. if (info.name == 'pano10-8&pano12-6') {
  678. console.log(4)
  679. }
  680. //if (info.boxType == 'battery' || info.boxType == 'air-hanging' || info.boxType == 'air' || info.category == 'battery' || info.category == 'air') {
  681. if (standards[info.boxType].atWall && standards[info.boxType].thick || force ) {
  682. //根据比例判断
  683. /* let r1 = Math.abs((center.x - skyBoxTight.position.x) / (center.z - skyBoxTight.position.z))
  684. let r2 = player.model.size.x / player.model.size.z
  685. if(!math.closeTo(r1,r2, 0.05)){
  686. if (r1<r2) {
  687. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  688. } else {
  689. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  690. }
  691. matchInfo.xProp = xProp
  692. matchInfo.yProp = yProp
  693. } */
  694. //根据距离判断
  695. let center = getBoxPos(info)
  696. let bound = safeBound
  697. let minXDiff = Math.min(center.x - bound.min.x, bound.max.x - center.x)
  698. let minYDiff = Math.min(center.z - bound.min.z, bound.max.z - center.z)
  699. let dirs = getPanosDir(info, center)
  700. let noX = dirs['x+'] == 0 || dirs['x-'] == 0,
  701. noZ = dirs['z+'] == 0 || dirs['z-'] == 0
  702. //yi6dsPTWwFM klkcWindow pano0-1&pano2-0
  703. if (dirs['x+'] == 0 && dirs['x-'] != 0) {
  704. minXDiff = bound.max.x - center.x
  705. } else if (dirs['x-'] == 0 && dirs['x+'] != 0) {
  706. minXDiff = center.x - bound.min.x
  707. }
  708. if (dirs['z+'] == 0 && dirs['z-'] != 0) {
  709. minYDiff = bound.max.z - center.z
  710. } else if (dirs['z-'] == 0 && dirs['z+'] != 0) {
  711. minYDiff = center.z - bound.min.z
  712. }
  713. let xWidthPossible = noZ ? 1 : 0,
  714. yWidthPossible = noX ? 1 : 0
  715. xWidthPossible += minXDiff - minYDiff
  716. if (!math.closeTo(xWidthPossible, yWidthPossible, 0.2) && (minXDiff < 0.7 || minYDiff < 0.7)) {
  717. if (xWidthPossible < yWidthPossible) {
  718. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  719. } else {
  720. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  721. }
  722. }
  723. if (!xProp) {
  724. if(!force){//force的话是fire等无方向的类型
  725. if (info.category) {
  726. //是box
  727. info.pose || (info.pose = getBoxPoseByPos(info, center))
  728. xWidthPossible += info.pose.xWidthPossible
  729. yWidthPossible += info.pose.yWidthPossible
  730. } else {
  731. traverse(info, info => {
  732. if (info.boxposes) {
  733. //是matchInfo
  734. info.boxposes.forEach(e => {
  735. xWidthPossible += e.xWidthPossible
  736. yWidthPossible += e.yWidthPossible
  737. })
  738. }
  739. })
  740. }
  741. }
  742. /* if(noX!=noZ){
  743. if(noX)xWidthPossible
  744. } */
  745. if (xWidthPossible > yWidthPossible) {
  746. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  747. } else {
  748. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  749. }
  750. }
  751. xProp && ((info.xProp = xProp), (info.yProp = yProp))
  752. return {xWidthPossible, yWidthPossible}
  753. }
  754. }
  755. let preDealBox = matchInfo => {
  756. if (matchInfo.preDealRes || !matchInfo.center) return
  757. matchInfo.preDealRes = {}
  758. matchInfo.boxType || getBoxType(matchInfo)
  759. let config = standards[matchInfo.boxType]
  760. let minWidth = config.widthNormal.min
  761. let needGetPose
  762. let dis = safeBound.distanceToPoint(matchInfo.center)
  763. if (matchInfo.name == 'pano2-5') {
  764. console.log(4)
  765. }
  766. if (dis > 0.3 && !config.tiny && !config.tinyXZ) {
  767. //Tmo1vLp9Q13: hlkcWindow超出才准确
  768. //tiny的位置优先级高于bound,因为他们可以确定bound
  769. /* matchInfo.str && matchInfo.str.includes('outsideBound') */
  770. //const shrink = minWidth * 0.85
  771. //addLabel(matchInfo.center, '原')
  772. let finalPos = matchInfo.center.clone().clamp(safeBound.min, safeBound.max)
  773. matchInfo.preDealRes.position = finalPos
  774. //addLabel(finalPos, 'finalPos')
  775. getBoxType(matchInfo)
  776. needGetPose = true
  777. }
  778. let center = getBoxPos(matchInfo)
  779. if (needGetPose || !matchInfo.boxposes) {
  780. matchInfo.boxposes = []
  781. ;[matchInfo.box0, matchInfo.box1].forEach(box => {
  782. box && matchInfo.boxposes.push(getBoxPoseByPos(box, center))
  783. })
  784. }
  785. //-----------------
  786. getBoxDirProp(matchInfo)
  787. }
  788. let getBoxPoseByPos = (box, centerPos, addDis = 0) => {
  789. //当得知box的大概位置时,求box在这个角度上的宽度、朝向
  790. //在这个方向看的box的宽度
  791. let config = standards[box.boxType]
  792. let angle = getBbox2Diff(box.bbox2[2], box.bbox2[0]) * Math.PI //角度的一半
  793. let dis = new THREE.Vector3().subVectors(box.pano.position, centerPos).setY(0).length() + addDis
  794. let projectWidth = 2 * Math.tan(angle) * dis //投影宽度 (准确的投影宽度无法求得,只能近似)
  795. let camDir = /* new THREE.Vector2(centerPos.x-box.pano.position.x, centerPos.z-box.pano.position.z).normalize() */ box.centerDir.clone().setY(0).normalize()
  796. let camTangent = math.getNormal({
  797. points: [
  798. { x: 0, y: 0 },
  799. /* camDir */ { x: camDir.x, y: camDir.z },
  800. ],
  801. }) //视线切线方向
  802. camTangent.x = Math.abs(camTangent.x)
  803. camTangent.y = Math.abs(camTangent.y)
  804. if (box.sid == 'pano4-6') {
  805. console.log(7)
  806. }
  807. const maxWidth = config.widthNormal.max
  808. const minWidth = config.widthNormal.min
  809. let minProjectWidth //= (camTangent.x + camTangent.y) * minWidth
  810. let maxProjectWidth //= (camTangent.x + camTangent.y) * maxWidth
  811. let maxX, maxY, minX, minY
  812. if (!standards[box.boxType].thick) {
  813. minProjectWidth = (camTangent.x + camTangent.y) * minWidth
  814. maxProjectWidth = (camTangent.x + camTangent.y) * maxWidth //该角度下该类型允许的最大投影距离
  815. maxX = THREE.MathUtils.clamp((projectWidth - minWidth * camTangent.y) / camTangent.x, minWidth, maxWidth) //可得x的最大值(假设y为最小值)
  816. maxY = THREE.MathUtils.clamp((projectWidth - minWidth * camTangent.x) / camTangent.y, minWidth, maxWidth) //可得y的最大值(假设x为最小值)
  817. minX = THREE.MathUtils.clamp((projectWidth - maxWidth * camTangent.y) / camTangent.x, minWidth, maxWidth) //可得x的最小值(假设y为最大值)
  818. minY = THREE.MathUtils.clamp((projectWidth - maxWidth * camTangent.x) / camTangent.y, minWidth, maxWidth) //可得y的最小值(假设x为最大值)
  819. } else {
  820. const minThick_ = config.thick.min
  821. const minWidth_ = config.width.min
  822. const maxThick_ = config.thick.max
  823. const maxWidth_ = config.width.max
  824. let maxProjectWidth1 = camTangent.x * maxWidth_ + camTangent.y * maxThick_
  825. let maxProjectWidth2 = camTangent.x * maxThick_ + camTangent.y * maxWidth_
  826. let minProjectWidth1 = camTangent.x * minWidth_ + camTangent.y * minThick_
  827. let minProjectWidth2 = camTangent.x * minThick_ + camTangent.y * minWidth_
  828. minProjectWidth = Math.min(minProjectWidth1, minProjectWidth2)
  829. maxProjectWidth = Math.max(maxProjectWidth1, maxProjectWidth2)
  830. let a = (camTangent.x + camTangent.y) * maxWidth
  831. //console.log('diffaaaaaa',maxProjectWidth,a, box.sid)
  832. maxX = THREE.MathUtils.clamp((projectWidth - minThick_ * camTangent.y) / camTangent.x, minThick_, maxWidth_) //可得x的最大值(假设y为最小值)
  833. maxY = THREE.MathUtils.clamp((projectWidth - minThick_ * camTangent.x) / camTangent.y, minThick_, maxWidth_) //可得y的最大值(假设x为最小值)
  834. minX = THREE.MathUtils.clamp((projectWidth - maxWidth_ * camTangent.y) / camTangent.x, minThick_, maxWidth_)
  835. minY = THREE.MathUtils.clamp((projectWidth - maxWidth_ * camTangent.x) / camTangent.y, minThick_, maxWidth_)
  836. }
  837. /*
  838. let maxX = projectWidth / camTangent.x //可得x的最大值(假设y为0)
  839. let maxY = projectWidth / camTangent.y //可得y的最大值(假设x为0)
  840. */
  841. //判断方向
  842. let o = { box, projectWidth, camTangent, maxProjectWidth, minProjectWidth, dis, maxX, maxY, minX, minY }
  843. if (config.atWall > 0 /* isType(box,battery) || isType(box,air) */) {
  844. //为了获取朝向
  845. o.xWidthPossible = -Math.abs(projectWidth - camTangent.x * maxWidth - camTangent.y * minWidth)
  846. o.yWidthPossible = -Math.abs(projectWidth - camTangent.x * minWidth - camTangent.y * maxWidth)
  847. //在接近45度时容易不准。另外如果被遮住一部分更会错,因此尽量不让被遮住的匹配
  848. }
  849. return o
  850. }
  851. let getPoseScore = (boxposes, boxType) => {
  852. let score = 0
  853. const minDis = 1.5
  854. /* if (boxposes[0].box.sid == 'pano12-13' && boxposes[1].box.sid == 'pano8-6') {
  855. console.log(4)
  856. } */
  857. boxposes.forEach(pose => {
  858. //pose.lowR = pose.dis < minDis ? Math.pow(THREE.MathUtils.smoothstep(pose.dis / minDis, 0, 1),2) : 1 //太近的话误差大
  859. pose.lowR = pose.dis < minDis ? Math.pow(pose.dis / minDis, 1.4) : 1 //太近的话误差大
  860. if (pose.projectWidth > pose.maxProjectWidth) {
  861. score += Math.pow((pose.projectWidth / pose.maxProjectWidth - 1) * pose.lowR, 2) * 500 //超过的话数字较大所以乘的数小一些
  862. } else if (/* isSingle && */ pose.projectWidth < pose.minProjectWidth) {
  863. score += Math.pow((pose.minProjectWidth / pose.projectWidth - 1) * pose.lowR, 2) * 500
  864. }
  865. let { min, max } = standards[boxType].widthNormal
  866. if ((standards[boxType].atWall == 1 && min < 0.3) || (boxposes.length == 2 && boxType == 'battery')) {
  867. let { min, max } = standards[boxType].widthNormal
  868. //let r = Math.max(0.001, (pose.projectWidth - min) / (max - min))
  869. let diff = max - min
  870. let r = math.linearClamp(pose.projectWidth, min, min + diff * 0.5, 600, 0)
  871. //if(boxposes.length == 2 && boxType == 'battery'){//由于battery经常出现遮挡,导致方向出错,因此尽量不匹配projectWidth较短的,尽管这本有可能是对的
  872. score += r
  873. //}
  874. /* if (min < 0.3 && r < 0.5) {
  875. //从贴近墙面的位置看侧面的话,容易被挡住,不准,尤其是电箱
  876. score += ((max - min) / r / min) * 5
  877. } */
  878. }
  879. })
  880. score = Math.min(score, 1300) //压低一点,因为得的宽度可能不准
  881. if (boxposes.length == 2) {
  882. //每一个方向对应有四个方向(每个象限一个)看到的projectWidth应该接近。
  883. //先把camTangent转化为第一个象限的
  884. let camTangent0 = new THREE.Vector2(Math.abs(boxposes[0].camTangent.x), Math.abs(boxposes[0].camTangent.y))
  885. let camTangent1 = new THREE.Vector2(Math.abs(boxposes[1].camTangent.x), Math.abs(boxposes[1].camTangent.y))
  886. let a = camTangent0.dot(camTangent1)
  887. if (a > 0.8) {
  888. //WcLVXvmV9AU
  889. //0.9: 25度之内. 0.8: 36.8度之内
  890. let diff = Math.abs(boxposes[0].projectWidth - boxposes[1].projectWidth)
  891. boxposes.score2 = a * diff * 1300 * boxposes[0].lowR * boxposes[1].lowR
  892. score += boxposes.score2
  893. //console.warn('在同一个方向看到的projectWidth应该接近。 ', diff)
  894. }
  895. boxposes.camTangentCos = a
  896. }
  897. //要不要加上minX等的差距?
  898. score = Math.min(score, 1200)
  899. return -score
  900. }
  901. let getBoxSize = info => {
  902. if (info.boxType == 'groundBar') {
  903. console.log(1)
  904. }
  905. if (info.size) return
  906. //console.warn('开始算 ' + info.name)
  907. let exStr = '',
  908. warnStr = ''
  909. let x, y //求对角线的向量 x>0,y>0
  910. //假设盒子的长宽为x,y (x>0,y>0),视线切线单位向量为(k,m),投影距离:x'k+y'm.(x'是正负x,y'是正负y)
  911. //由于盒子的对角线有四个可选方向,(类似四个象限) 则需要能使投影距离最长的一个对角线向量。
  912. //如,当k<0,m>0时,要使xk+ym 最大,必有x<0,y>0. 故 x = -x', y = y', 故 投影距离:x'k+y'm = x(-k)+ym 。
  913. //故无论km的符号如何,只要变为正数,再去联立方程即可得xy。(相当于切线转到第一象限)
  914. //注:但是因为无法获取准确的投影距离(角平分线左右两边的端点到角平分线的距离不相等,垂足也无法确定),所以所算的误差非常大。
  915. if (info.name == 'pano6-13&pano4-13') {
  916. console.log(6)
  917. }
  918. let center = getBoxPos(info)
  919. let oriX, oriY
  920. if (info.predictSize) {
  921. ;(x = oriX = info.predictSize.x), (y = oriY = info.predictSize.y)
  922. } else {
  923. if (info.box1) {
  924. let x1 = info.boxposes[0].camTangent.x,
  925. x2 = info.boxposes[1].camTangent.x,
  926. y1 = info.boxposes[0].camTangent.y,
  927. y2 = info.boxposes[1].camTangent.y,
  928. w1 = /* info.boxposes[0].projectWidth, */ THREE.MathUtils.clamp(info.boxposes[0].projectWidth, info.boxposes[0].minProjectWidth, info.boxposes[0].maxProjectWidth * 1.1), //校准。如果projectwidth不准那算出来更不准. 但XswQxwmn2ZC的里侧电池是前者更准
  929. w2 = /* info.boxposes[1].projectWidth */ THREE.MathUtils.clamp(info.boxposes[1].projectWidth, info.boxposes[1].minProjectWidth, info.boxposes[1].maxProjectWidth * 1.1)
  930. //如果识别到柜门上,(柜体被遮住了),整体中心就会在柜门上,且厚度小于真实值。
  931. if (x1 == 0) {
  932. y = w1
  933. x = (w2 - y2 * y) / x2
  934. } else {
  935. //联立方程得:
  936. y = (w2 - (x2 / x1) * w1) / (y2 - (x2 / x1) * y1)
  937. x = (w1 - y1 * y) / x1
  938. }
  939. //console.log('xy', { x, y })
  940. ;(x < 0.3 || x > 1.4) && (exStr += ' x:' + math.toPrecision(x, 2))
  941. ;(y < 0.3 || y > 1.4) && (exStr += ' y:' + math.toPrecision(y, 2))
  942. if (y < 0 || x < 0) {
  943. //console.log('<0 ?????????')
  944. warnStr = x < 0 ? 'x<0!' : 'y<0!'
  945. }
  946. ;(oriX = x), (oriY = y)
  947. } else {
  948. //single pano data
  949. //将maxX maxY 限定在标准范围内
  950. if (info.xProp) {
  951. let widthValue = standards[info.boxType].width
  952. let thickValue = standards[info.boxType].thick
  953. let maxX, maxY, minX, minY
  954. if (info.xProp == 'width') {
  955. /* x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, widthValue.min, widthValue.max)
  956. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, thickValue.min, thickValue.max)
  957. */
  958. maxX = THREE.MathUtils.clamp(info.boxposes[0].maxX, widthValue.min, widthValue.max) //AG0bi2fhb3 需要将得到的minX等这四项都clamp后再平均
  959. maxY = THREE.MathUtils.clamp(info.boxposes[0].maxY, thickValue.min, thickValue.max)
  960. minX = THREE.MathUtils.clamp(info.boxposes[0].minX, widthValue.min, widthValue.max)
  961. minY = THREE.MathUtils.clamp(info.boxposes[0].minY, thickValue.min, thickValue.max)
  962. } else {
  963. /* x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, thickValue.min, thickValue.max)
  964. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, widthValue.min, widthValue.max)
  965. */
  966. maxX = THREE.MathUtils.clamp(info.boxposes[0].maxX, thickValue.min, thickValue.max)
  967. maxY = THREE.MathUtils.clamp(info.boxposes[0].maxY, widthValue.min, widthValue.max)
  968. minX = THREE.MathUtils.clamp(info.boxposes[0].minX, thickValue.min, thickValue.max)
  969. minY = THREE.MathUtils.clamp(info.boxposes[0].minY, widthValue.min, widthValue.max)
  970. }
  971. x = oriX = (maxX + minX) / 2
  972. y = oriY = (maxY + minY) / 2
  973. } else {
  974. //x = oriX = y = oriY = (min+max)/2
  975. let standard = standards[info.boxType].widthNormal
  976. x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, standard.min, standard.max)
  977. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, standard.min, standard.max)
  978. }
  979. }
  980. //按正常来说,得到的x,y都应>0,但是由于箱子会被遮挡,导致投影宽度比真实的小,算出的也不准,可能是负数
  981. //所以手动将过小的宽度矫正
  982. }
  983. /* if(info.name == "pano2-6"){
  984. console.log(7)
  985. } */
  986. let height
  987. if (standards[info.boxType].bottom) {
  988. //悬挂的
  989. //挂式空调最好把长宽固定。 不过极少出错
  990. //center.y -= 0.1 //很可能过高
  991. height = standards[info.boxType].height.standard
  992. getBoxBtm(info)
  993. if (height) {
  994. let d = center.y - info.btmPos.y
  995. center.y -= THREE.MathUtils.clamp((d - height / 2) / 2, -0.1, 0.1) //如果中心点到底部的距离和height的一半不同,中心点移动差值的一半
  996. } else {
  997. let btmY = info.btmPos.y
  998. /* let ys = [info.btmPos.y]//info.btmPos.y蛮不准的
  999. if(info.box0){
  1000. ys.push(info.box0.btmPos.y)
  1001. }
  1002. if(info.box1){
  1003. ys.push(info.box1.btmPos.y)
  1004. }
  1005. btmY = ys.reduce((w,c)=>{return w+c},0)
  1006. btmY/=ys.length //平均 */
  1007. height = (center.y - btmY) * 2
  1008. }
  1009. } else {
  1010. if (!info.topPos) getBoxTop(info)
  1011. height = info.topPos.y - groundY
  1012. }
  1013. let o = restrictSize(x, height, y, info)
  1014. ;(x = o.x), (height = o.y), (y = o.z)
  1015. if (standards[info.boxType].widthSame) {
  1016. x = y = (x + y) / 2
  1017. }
  1018. info.size = new THREE.Vector3(x, height, y)
  1019. info.sizeAdjust = Math.pow(Math.abs(x - oriX), 1.3) + Math.pow(Math.abs(y - oriY), 1.3) //计算得到的值和标准值之间的差距,可以反映该info的匹配分值
  1020. if (info.sizeAdjust) info.score = (info.score || 0) - Math.min(info.sizeAdjust * 100, 400)
  1021. ;(info.size.oriX = oriX), (info.size.oriY = oriY)
  1022. ;(info.exStr = exStr), (info.warnStr = warnStr)
  1023. }
  1024. let restrictSize = (x, y, z, info) => {
  1025. let s
  1026. let { xProp, yProp } = info
  1027. if (xProp != void 0) {
  1028. var { min, max } = standards[info.boxType][xProp]
  1029. x = THREE.MathUtils.clamp(x, min, max)
  1030. var { min, max } = standards[info.boxType][yProp]
  1031. z = THREE.MathUtils.clamp(z, min, max)
  1032. s = true
  1033. }
  1034. if (!s) {
  1035. var { min, max } = standards[info.boxType].widthNormal
  1036. x = THREE.MathUtils.clamp(x, min, max)
  1037. z = THREE.MathUtils.clamp(z, min, max)
  1038. }
  1039. var { min, max } = standards[info.boxType].height
  1040. y = THREE.MathUtils.clamp(y, min, max)
  1041. return { x, y, z }
  1042. }
  1043. let getMixBox = (box0, box1) => {
  1044. //重叠部分
  1045. let box = new THREE.Box2()
  1046. box.min.set(Math.max(box0.min.x, box1.min.x), Math.max(box0.min.y, box1.min.y))
  1047. box.max.set(Math.min(box0.max.x, box1.max.x), Math.min(box0.max.y, box1.max.y))
  1048. return box
  1049. }
  1050. let getLeftRight = boxArr => {
  1051. //获取pano的boxes中最左和最右的bbox.x
  1052. let lefts = boxArr.map(e => e.bbox2[0])
  1053. let rights = boxArr.map(e => e.bbox2[2])
  1054. lefts.sort((a, b) => getBbox2Diff(a, b))
  1055. rights.sort((a, b) => getBbox2Diff(b, a))
  1056. let leftX = lefts[0] //最左
  1057. let rightX = rights[0] //最右
  1058. return {
  1059. leftX,
  1060. rightX,
  1061. }
  1062. }
  1063. let searchPair = (beginItem, group0_, group1_, parentPairs, resultPairs) => {
  1064. let pair = [] //只能是来自group0的
  1065. if (parentPairs) {
  1066. //元结点裂变出多个,来装新的pair
  1067. let i = resultPairs.indexOf(parentPairs)
  1068. resultPairs.splice(i, 1)
  1069. }
  1070. for (let j = 0; j < group1_.length; j++) {
  1071. pair = [beginItem, group1_[j]]
  1072. let newPairs //用来存放该组pair
  1073. if (parentPairs) {
  1074. newPairs = parentPairs.slice(0) //复制
  1075. newPairs.push(pair)
  1076. } else {
  1077. newPairs = [pair] //新的容器
  1078. }
  1079. resultPairs.push(newPairs)
  1080. let newGroup0 = group0_.slice(0)
  1081. let newGroup1 = group1_.slice(0)
  1082. let index = newGroup0.indexOf(pair[0])
  1083. newGroup0.splice(index, 1)
  1084. index = newGroup1.indexOf(pair[1])
  1085. newGroup1.splice(index, 1)
  1086. if (newGroup0.length > 0 && newGroup1.length > 0) {
  1087. searchPair(newGroup0[0], newGroup0, newGroup1, newPairs, resultPairs)
  1088. }
  1089. }
  1090. }
  1091. export default class PanoBoxFrame extends THREE.Group {
  1092. constructor(player_, ifAnalyze, dataList) {
  1093. super()
  1094. player = player_
  1095. player.model.add(this)
  1096. this.ifAnalyze = ifAnalyze
  1097. this.wireframes = new THREE.Object3D()
  1098. this.wireframes.name = 'wireframes'
  1099. this.add(this.wireframes)
  1100. this.matchScoreMap = {}
  1101. this.bindEvents()
  1102. meshGroup = new THREE.Object3D()
  1103. meshGroup.name = 'testBox'
  1104. this.add(meshGroup)
  1105. this.compute(dataList)
  1106. }
  1107. async compute(dataList) {
  1108. startTime = Date.now()
  1109. this.datas = {}
  1110. this.datasMixed = {}
  1111. this.boxesSolid = boxesSolid
  1112. let compu = 0
  1113. let beginCompute = () => {
  1114. //获取匹配分数
  1115. let getMatchScore = (box0, box1, { isSingle, center, onlyGet, dontCheckDis } = {}) => {
  1116. let name0 = box0.sid + '&' + box1.sid
  1117. let name1 = box1.sid + '&' + box0.sid
  1118. let boxType = getBoxType(box0)
  1119. let matchInfo0 = this.matchScoreMap[boxType][name0]
  1120. let matchInfo1 = this.matchScoreMap[boxType][name1]
  1121. let matchInfo = matchInfo0 || matchInfo1
  1122. if (onlyGet) return matchInfo
  1123. let name
  1124. if (!matchInfo) {
  1125. name = name0
  1126. matchInfo = { name, box0, box1, center }
  1127. this.matchScoreMap[boxType][name] = matchInfo
  1128. } else {
  1129. return matchInfo
  1130. }
  1131. if (name == 'pano6-9&pano8-4') {
  1132. console.log(5)
  1133. }
  1134. getBoxBase(box0)
  1135. getBoxBase(box1)
  1136. let A = box0.pano.position.clone()
  1137. let B = box1.pano.position.clone()
  1138. let AB = new THREE.Vector3().subVectors(B, A)
  1139. let AB2d = new THREE.Vector2(AB.x, AB.z).normalize()
  1140. let AP12d = center ? new THREE.Vector2(center.x - A.x, center.z - A.z).normalize() : new THREE.Vector2(box0.centerDir.x, box0.centerDir.z).normalize()
  1141. let BP22d = center ? new THREE.Vector2(center.x - B.x, center.z - B.z).normalize() : new THREE.Vector2(box1.centerDir.x, box1.centerDir.z).normalize()
  1142. let angleA = Math.acos(AB2d.dot(AP12d))
  1143. let angleB = Math.PI - Math.acos(AB2d.dot(BP22d))
  1144. let score = 100,
  1145. str = []
  1146. if (angleA + angleB > Math.PI + 0.2) {
  1147. //无交点(比180大是因为中心角度有误差,所以给一定的容错)
  1148. //console.log(`${panoId0}的第${box0.index}个与${panoId1}的第${box1.index}个因角度大于180度 不匹配`)
  1149. return Object.assign(matchInfo, { score: -5000, str: ['angle>180'] })
  1150. }
  1151. if (box0.type != box1.type) {
  1152. return Object.assign(matchInfo, { score: -5000, str: ['typeNotSame'] })
  1153. }
  1154. if (matchInfo.dirAngleXZ == void 0) {
  1155. matchInfo.dirAngleXZ = THREE.MathUtils.radToDeg(Math.acos(AP12d.dot(BP22d))) //需要尽量接近90度算出来的交点会比较准
  1156. matchInfo.minAng = Math.min(180 - matchInfo.dirAngleXZ, matchInfo.dirAngleXZ) //角度小的getIntersect2容易算不准
  1157. if (isSingle) {
  1158. let bestDisSquared = 2
  1159. //单个匹配单个,而非多个匹配多个(没有固定到两个漫游点),所以可以直接寻找最优角度
  1160. score += Math.sin(THREE.MathUtils.degToRad(matchInfo.dirAngleXZ)) * 300
  1161. score += matchInfo.dirAngleXZ //另外角度越大越不容易偏向一边
  1162. score -= Math.abs(getBoxPos(box0).distanceToSquared(box0.pano.position) - bestDisSquared) * 10
  1163. score -= Math.abs(getBoxPos(box1).distanceToSquared(box1.pano.position) - bestDisSquared) * 10
  1164. }
  1165. }
  1166. let shinkRatio = 1
  1167. let btmPos0 = box0.btmPos || box0.btmPosPredict //fire类型先用btmPosPredict,测定groundY后才有btmPos
  1168. let btmPos1 = box1.btmPos || box1.btmPosPredict
  1169. if (!dontCheckDis) {
  1170. //let r = box0.boxType == 'air' ? 1 : box0.boxType == 'cabinet' ? 0.9 : 0.7 //随着宽度增加而降低
  1171. let r = THREE.MathUtils.clamp(0.8 / standards[boxType].widthNormal.max, 0.6, 2) //随着宽度增加而降低 UWrshepp0G5的fire
  1172. if (!standards[boxType].bottom && btmPos0 && btmPos1) {
  1173. //注:挂空调不应使用btmPosPredict
  1174. let d = btmPos0.distanceToSquared(btmPos1)
  1175. matchInfo.btmPosPreDis = d
  1176. score -= d * 1300 * r * shinkRatio
  1177. if (box1.topPos) {
  1178. let a = box0.topPos.distanceToSquared(box1.topPos)
  1179. matchInfo.topPosPreDis = a
  1180. let u = a * 700 * r * shinkRatio
  1181. let AP0 = new THREE.Vector2(btmPos0.x - A.x, btmPos0.z - A.z).lengthSq()
  1182. let AP1 = new THREE.Vector2(btmPos1.x - B.x, btmPos1.z - B.z).lengthSq()
  1183. if (AP0 < 0.4 || AP1 < 0.4) u *= 0.3 //太近
  1184. score -= u
  1185. }
  1186. } else if (box0.posAtWall && box1.posAtWall) {
  1187. //
  1188. let d = box0.posAtWall.distanceToSquared(box1.posAtWall)
  1189. matchInfo.wallPosPreDis = d
  1190. score -= d * 200 * r //墙面不准所以分低 ftMTQIrs79
  1191. d = box0.btmPosOri.distanceToSquared(box1.btmPosOri) //还是加一下
  1192. matchInfo.btmPosPreDis = d
  1193. score -= d * 200 * r * shinkRatio
  1194. /* let h0 = box0.topPos.y - box0.btmPos.y
  1195. let h1 = box1.topPos.y - box1.btmPos.y
  1196. score -= Math.abs(h0-h1) * 3000 * r * shinkRatio //高度差 倾斜角度大的不准
  1197. */
  1198. }
  1199. }
  1200. if (!matchInfo.center) {
  1201. let o = getIntersect2(A, box0.centerDir, B, box1.centerDir)
  1202. matchInfo.center = o.pos3d.clone()
  1203. /* let o2 = math.getLineIntersect({ A, B, p1: A.clone().add(box0.centerDir), p2:B.clone().add(box1.centerDir) })
  1204. matchInfo.center2 = o2.pos3d.clone() */
  1205. /* if (name == "pano16-4&pano18-5") {
  1206. addLine(A, box0.centerBtmDir, 10), addLine(B, box1.centerBtmDir, 10)
  1207. } */
  1208. //验证是否漫游点到中心点的方向和centerDir一样
  1209. let dir0 = new THREE.Vector3().subVectors(o.pos3d, A).normalize()
  1210. let dir1 = new THREE.Vector3().subVectors(o.pos3d, B).normalize()
  1211. let sum = dir0.dot(box0.centerDir) + dir1.dot(box1.centerDir)
  1212. let wrongDir = sum < 1.95
  1213. score -= (2 - sum) * 10000
  1214. if (wrongDir) {
  1215. str.push('wrongDir')
  1216. return Object.assign(matchInfo, { score: score - 5000, str })
  1217. }
  1218. if (!dontCheckDis && !standards[boxType].bottom && box0.btmPos && box1.btmPos) {
  1219. //墙壁位置不准所以不用 KK-ftMTQIrs79
  1220. let p0 = new THREE.Vector2(box0.btmPos.x, box0.btmPos.z)
  1221. let p1 = new THREE.Vector2(box1.btmPos.x, box1.btmPos.z)
  1222. let p = new THREE.Vector2(matchInfo.center.x, matchInfo.center.z)
  1223. let dis = p0.distanceToSquared(p) + p1.distanceToSquared(p)
  1224. let s = math.linearClamp(matchInfo.minAng, 0, 20, 0, 1)
  1225. score -= dis * 1500 * s //如果距离较远就说明算的center误差大,不可信。可能有一个框不准确
  1226. matchInfo.centerDrift = dis
  1227. }
  1228. getBoxBtm(matchInfo)
  1229. let cr //getIntersect2结果的权重
  1230. if (standards[box0.boxType].atWall == 1) {
  1231. cr = math.linearClamp(matchInfo.minAng, 2, 15, 0, 1) //墙壁误差大,所以尽量完全依赖cIntersect。。。后期如果该墙壁校准了可以调整
  1232. } else {
  1233. cr = math.linearClamp(matchInfo.minAng, 2, 20, 0, 0.4)
  1234. }
  1235. let predict0 = (!standards[boxType].bottom && box0.btmPos) || box0.posAtWall || matchInfo.topPos //在墙上的除非角度小,否则不考虑cIntersect
  1236. let predict1 = (!standards[boxType].bottom && box1.btmPos) || box1.posAtWall || matchInfo.topPos
  1237. //相对来说btmPos要比center准一点?因为center有在两个维度上的误差
  1238. const btmRatio = 0.5
  1239. let cIntersect = new THREE.Vector3().addVectors(matchInfo.center.clone().multiplyScalar(1 - btmRatio), matchInfo.btmPos.clone().multiplyScalar(btmRatio)).setY(o.pos3d.y)
  1240. if (predict0 && predict1) {
  1241. matchInfo.center = new THREE.Vector3()
  1242. .addVectors(
  1243. cIntersect.clone().multiplyScalar(cr),
  1244. predict0
  1245. .clone()
  1246. .add(predict1)
  1247. .multiplyScalar((1 / 2) * (1 - cr))
  1248. )
  1249. .setY(o.pos3d.y)
  1250. } else {
  1251. matchInfo.center = cIntersect
  1252. }
  1253. matchInfo.cIntersect = cIntersect
  1254. //addLabel(matchInfo.center, matchInfo.name + '-c')
  1255. }
  1256. getBoxType(matchInfo)
  1257. /* if (matchInfo.boxType != box0.type || matchInfo.boxType != box1.type) {
  1258. ;(score -= 1000), str.push('typeNotSame2')
  1259. } */
  1260. {
  1261. let vec0 = new THREE.Vector3().subVectors(box0.pano.position, matchInfo.center)
  1262. let vec1 = new THREE.Vector3().subVectors(box1.pano.position, matchInfo.center)
  1263. if (vec0.x * vec1.x > 0 && vec0.z * vec1.z > 0) {
  1264. //同一个象限(center会偏向一侧)
  1265. score -= 200
  1266. }
  1267. }
  1268. if (!safeBound.containsPoint(matchInfo.center)) {
  1269. let dis = safeBound.distanceToPoint(matchInfo.center)
  1270. //console.log(`${panoId0}的第${box0.index}个与${panoId1}的第${box1.index}个因中心点在bounding外不匹配`, center, 'dis: ' + dis)
  1271. ;(score -= 1000 * dis * dis), str.push('outsideBound')
  1272. Object.assign(matchInfo, { score, str, center: matchInfo.center, disToBound: dis })
  1273. if (dis > 0.5) return matchInfo
  1274. }
  1275. //检查宽度
  1276. let boxposes
  1277. let checkWidth = () => {
  1278. boxposes = []
  1279. ;[box0, box1].forEach(box => {
  1280. let pose = getBoxPoseByPos(box, matchInfo.center)
  1281. boxposes.push(pose)
  1282. //如果超出标准,基本上这二者不匹配;但过小的话,有可能是被遮挡所以残缺,因此不予过滤
  1283. })
  1284. }
  1285. checkWidth()
  1286. score += getPoseScore(boxposes, boxType /* isSingle */) //根据投影信息预测的长度再得匹配分数
  1287. compu++
  1288. return Object.assign(matchInfo, { score: score, str, /* diffHalfHeight, */ boxposes })
  1289. }
  1290. this.rows = {}
  1291. /* let getchainNext = (left, end, chain, boxes) => {
  1292. chain.push(left)
  1293. if (left == end) return boxes.chains.push(chain)
  1294. let nodes = boxes.relationships.filter(pair => pair.includes(left))
  1295. let rights = nodes.map(pair => pair.find(e => e != left))
  1296. rights = rights.filter(e => !chain.includes(e) && boxes.indexOf(e) > boxes.indexOf(left))
  1297. rights.forEach(right => {
  1298. getchainNext(right, end, chain.slice(), boxes)
  1299. })
  1300. } */
  1301. let getPanoBigRowBox = (panoBoxes, { reason = 'row' } = {}) => {
  1302. //将一个pano中的所有boxes分组,识别哪些是一排的。也可用于识别融合
  1303. let pano = panoBoxes[0].pano
  1304. const category = panoBoxes[0].category
  1305. let type = category + '|' + reason
  1306. this.rows[type] || (this.rows[type] = {})
  1307. if (this.rows[type][pano.id]) return this.rows[type][pano.id]
  1308. let bigBoxes
  1309. let bigBox = {
  1310. sid: 'pano' + pano.id + (reason == 'mix' ? '-mix' : '-row'),
  1311. pano,
  1312. category: reason == 'mix' ? category : 'rowBigBox',
  1313. boxType: reason == 'mix' ? panoBoxes[0].boxType : 'rowBigBox',
  1314. }
  1315. let rows = []
  1316. for (let i = 0; i < panoBoxes.length; i++) {
  1317. let box0 = panoBoxes[i]
  1318. getBoxBase(box0)
  1319. let [left0, right0] = [box0.bbox2[0], box0.bbox2[2]]
  1320. for (let j = i + 1; j < panoBoxes.length; j++) {
  1321. let box1 = panoBoxes[j]
  1322. getBoxBase(box1)
  1323. if (box0.boxType != box0.boxType) continue //类型不同
  1324. let [left1, right1] = [box1.bbox2[0], box1.bbox2[2]]
  1325. let d1 = getBbox2Diff(left1, right0),
  1326. d2 = getBbox2Diff(left1, left0),
  1327. d3 = getBbox2Diff(left0, right1)
  1328. if (box0.sid == 'pano2-4' && box1.sid == 'pano2-5') {
  1329. console.log(9)
  1330. }
  1331. const min = reason == 'mix' ? 0.004 : 0.003 //mix代表寻找分裂的重新融合到一起
  1332. if ((d1 <= min && d2 >= min) || (d3 <= min && d2 <= min)) {
  1333. //边框交接
  1334. let atEdgeMight = left1 < 0.002 && right0 > 0.998 ? [left1, right0] : left0 < 0.002 && right1 > 0.998 ? [left0, right1] : null //有在全景图的边界的可能性
  1335. //if (reason == 'mix' && box0.category == typeNames.cabinet && !atEdgeMight) continue //柜子容易并排,尽量不融合 //再看,啥意思,没懂
  1336. if (reason == 'mix' && !atEdgeMight) continue //不在边缘
  1337. const { max } = standards[box0.boxType].widthNormal //standards[box0.btmPos ? category : 'air-hanging'].widthNormal
  1338. const tolerate = max * max * (reason == 'mix' ? 0.7 : 1.8) //yDCiaTQvRYn:row不能低于1.5
  1339. let p0 = standards[box0.boxType].atWall == 1 ? box0.posAtWall : reason == 'mix' ? box0.btmPosOri || box0.btmPosPredict : box0.btmPos
  1340. let p1 = standards[box1.boxType].atWall == 1 ? box1.posAtWall : reason == 'mix' ? box1.btmPosOri || box1.btmPosPredict : box1.btmPos
  1341. //let p0 = box0.type == 'air-hanging' ? box0.posAtWall : reason == 'mix' ? box0.btmPosOri : box0.btmPos
  1342. //let p1 = box1.type == 'air-hanging' ? box1.posAtWall : reason == 'mix' ? box1.btmPosOri : box1.btmPos
  1343. let dis = p0.distanceToSquared(p1)
  1344. if (reason == 'mix') {
  1345. let allY = box0.bbox2[3] - box0.bbox2[1] + (box1.bbox2[3] - box1.bbox2[1]) //各自高度和
  1346. let wholeY = Math.max(box0.bbox2[3], box1.bbox2[3]) - Math.min(box0.bbox2[1], box1.bbox2[1]) //总跨越高度
  1347. let coverY = allY - wholeY //重合区域的y高度,可为负数
  1348. let disY = (1 - coverY / wholeY + (wholeY - coverY) * 3) * 4 * tolerate //既要考虑占比也要考虑差值
  1349. dis += disY //SGyhEzZNGP9案例:虽然是atEdge但并不应该融合,便通过disY来阻挡 ; MW6MEeCOy9Y:pano16-15
  1350. //console.log('disY',disY, box0.sid, box1.sid )
  1351. let atEdgePossib = atEdgeMight ? 0.002 / (atEdgeMight[0] + (1 - atEdgeMight[1])) : 0 // 两条线越接近越可能融合
  1352. atEdgePossib = Math.min(6, atEdgePossib) //原本计算得 min:1, max:Infinity
  1353. dis -= atEdgePossib * tolerate //给点点优势
  1354. }
  1355. /* if(box0.sid == "pano2-0"){
  1356. console.log('dis',dis,'tolerate',tolerate,[box0, box1],disY)
  1357. }
  1358. if (box0.sid == 'pano2-1' && box1.sid == 'pano2-4') {
  1359. reason == 'mix' && console.log(dis, tolerate, box0.sid, box1.sid)
  1360. }*/
  1361. if (dis < tolerate) {
  1362. //reason == 'mix' && console.log('-------------------')
  1363. common.pushToGroupAuto([box0, box1], rows)
  1364. }
  1365. }
  1366. }
  1367. }
  1368. //一排箱子的角度范围不可超过180度,因为不可能站在箱子上拍,所以超过的话肯定有边缘的不在这一排中。
  1369. //可判断边缘箱子的是否角度偏大,一般中间的被遮挡所以偏小
  1370. rows.forEach(boxes => {
  1371. //从左到右排序
  1372. boxes.sort((a, b) => {
  1373. //但因有的box跨越到别的box区域,所以这个顺序不准确
  1374. return getBbox2Diff(a.bbox2CenterX, b.bbox2CenterX)
  1375. })
  1376. })
  1377. //去除不在一条直线上的连接. 当bound超出后就断开
  1378. if (reason == 'row') {
  1379. rows.slice(0).forEach(boxes => {
  1380. if (boxes.length >= 2) {
  1381. let removes = [],
  1382. bound = new THREE.Box2(),
  1383. size = new THREE.Vector2(),
  1384. maxW = 0.6
  1385. for (let i = 0, j = boxes.length; i < j; i++) {
  1386. let box = boxes[i]
  1387. let pos2d = new THREE.Vector2(box.btmPos.x, box.btmPos.z)
  1388. bound.expandByPoint(pos2d)
  1389. bound.getSize(size)
  1390. let min = Math.min(size.x, size.y)
  1391. if (min > maxW) {
  1392. removes.push([boxes[i], boxes[i - 1]])
  1393. bound = new THREE.Box2()
  1394. bound.expandByPoint(pos2d)
  1395. console.log('removes', size)
  1396. }
  1397. //console.log('removes',k, box1.sid)
  1398. }
  1399. if (removes.length) {
  1400. console.log(
  1401. '去除错误row连接',
  1402. removes.map(e => e.map(a => a.sid))
  1403. )
  1404. let { newGroups } = common.disconnectGroup(removes, rows)
  1405. //if(newGroups.length>1){//分裂成多组了,重新计算
  1406. // console.log(newGroups)
  1407. //}
  1408. }
  1409. }
  1410. })
  1411. rows.forEach(boxes => {
  1412. //从左到右重新排序
  1413. boxes.sort((a, b) => {
  1414. //但因有的box跨越到别的box区域,所以这个顺序不准确
  1415. return getBbox2Diff(a.bbox2CenterX, b.bbox2CenterX)
  1416. })
  1417. })
  1418. }
  1419. rows.sort((a, b) => {
  1420. return b.length - a.length
  1421. }) //箱子数量从大到小排序
  1422. bigBoxes = rows.map((boxes, i) => {
  1423. let { leftX, rightX } = getLeftRight(boxes) //最左
  1424. let topY = boxes.slice().sort((a, b) => a.bbox2[1] - b.bbox2[1])[0].bbox2[1]
  1425. let btmY = boxes.slice().sort((a, b) => b.bbox2[3] - a.bbox2[3])[0].bbox2[3]
  1426. let rowBigBox = Object.assign({}, bigBox, {
  1427. boxes,
  1428. bbox2: [leftX, topY, rightX, btmY], //整排的bbox
  1429. left: boxes.find(e => e.bbox2[0] == leftX),
  1430. right: boxes.find(e => e.bbox2[2] == rightX),
  1431. })
  1432. let p0 = getBoxPos(rowBigBox.left)
  1433. let p1 = getBoxPos(rowBigBox.right)
  1434. let vec = new THREE.Vector2(p0.x - p1.x, p0.z - p1.z)
  1435. rowBigBox.k = Math.abs(vec.x / vec.y)
  1436. rowBigBox.predictLen = (rowBigBox.k > 1 ? Math.abs(vec.x) : Math.abs(vec.y)) + 0.6 //加入一个宽度
  1437. /* if(boxes.length <= boxes.relationships.length){//多条链(为了识别一个box嵌套多个的情况。不过后来在开头时处理了一部分)
  1438. boxes.chains = []
  1439. getchainNext(left,right,[], boxes )
  1440. let aveAngle = (getBbox2Diff(left.bbox2[2], left.bbox2[0]) + getBbox2Diff(right.bbox2[2], right.bbox2[0]) ) / 2 -0.01 //首尾的angle平均数。但如果这两个不准那就导致整体出错了
  1441. let middleAngle = getBbox2Diff(right.bbox2[0], left.bbox2[2])
  1442. let counts = boxes.chains.map(e=>e.length)
  1443. counts.sort((a,b)=>a-b)
  1444. let min = counts[0],max = counts[counts.length-1]
  1445. let r = [], cur = min;
  1446. while(cur<=max){
  1447. r.push({cur, diff:Math.abs((middleAngle / (cur-2) - aveAngle)}) //加 0.01是因为增加边缘
  1448. cur++
  1449. }
  1450. r.sort((a,b)=>a.diff-b.diff)
  1451. rowBigBox.predictBoxCount = r[0].cur
  1452. //---------
  1453. let goodCountChains = boxes.chains.filter(e=>e.length == rowBigBox.predictBoxCount)
  1454. if(goodCountChains.length == 1) rowBigBox.bestChain = goodCountChains[0]
  1455. else{
  1456. goodCountChains = goodCountChains.map((chain,i)=>{
  1457. let j = 1, diff=0 //中间的box的angle的方差
  1458. while(j<rowBigBox.predictBoxCount){
  1459. let angle = getBbox2Diff(chain[j].bbox2[2], chain[j].bbox2[0])
  1460. diff += Math.pow(angle - aveAngle, 2)
  1461. j++;
  1462. }
  1463. return {diff, chain}
  1464. })
  1465. goodCountChains.sort((a,b)=>a.diff-b.diff)
  1466. rowBigBox.bestChain = goodCountChains[0].chain
  1467. }
  1468. console.log('getChains',boxes.chains, 'predictBoxCount',rowBigBox.predictBoxCount, r)
  1469. } */
  1470. return rowBigBox
  1471. })
  1472. if (reason != 'mix') {
  1473. panoBoxes.forEach(box => {
  1474. //加入单个的
  1475. if (!rows.some(row => row.includes(box))) {
  1476. let boxBig = Object.assign({}, bigBox, {
  1477. bbox2: box.bbox2,
  1478. boxes: [box],
  1479. left: box,
  1480. right: box,
  1481. })
  1482. bigBoxes.push(boxBig)
  1483. }
  1484. })
  1485. }
  1486. //mix的之前的btm因pose错误而延伸了不对的depth所以不准
  1487. bigBoxes.forEach(bigBox => {
  1488. bigBox.sid += '-' + bigBox.boxes.map(e => e.index).join(',')
  1489. /* if (bigBox.sid == 'pano0-rowBigBox-1,0,2,4') {
  1490. console.log(3)
  1491. } */
  1492. if (reason == 'row') {
  1493. //取平均值
  1494. if (bigBox.boxes[0].btmPos) {
  1495. bigBox.btmPos = bigBox.boxes.reduce((w, c) => w.add(c.btmPos), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1496. //addLabel(bigBox.btmPos,'b_'+bigBox.sid, {bgcolor:'#f93',a:0.4})
  1497. }
  1498. if (bigBox.boxes[0].topPos) {
  1499. bigBox.topPos = bigBox.boxes.reduce((w, c) => w.add(c.topPos), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1500. }
  1501. if (bigBox.boxes[0].posAtWall) {
  1502. bigBox.posAtWall = bigBox.boxes.reduce((w, c) => w.add(c.posAtWall), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1503. }
  1504. }
  1505. //mix的需要合并后计算才准确
  1506. })
  1507. this.rows[type][pano.id] = bigBoxes //当前pano的所有row
  1508. return bigBoxes
  1509. }
  1510. /* let getPanoBoxAngleTrend = rowBox => {
  1511. //顺时针方向该pano的box角度范围是越来越大还是越来越小
  1512. let diffs = []
  1513. let angles = rowBox.boxes.map(box => getBbox2Diff(box.bbox2[2], box.bbox2[0]))
  1514. for (let i = 0, j = angles.length; i < j - 1; i++) {
  1515. //得所有相邻之间的差
  1516. let a0 = angles[i],
  1517. a1 = angles[i + 1]
  1518. diffs.push(a1 - a0)
  1519. }
  1520. diffs.sort((a, b) => a - b)
  1521. return diffs[Math.floor(diffs.length / 2)] //中位数
  1522. } */
  1523. /* let getBoxCount = (rowBigBox)=>{
  1524. return rowBigBox.predictBoxCount || rowBigBox.boxes.length
  1525. } */
  1526. let getReverseInfo = (rowBigBox0, rowBigBox1) => {
  1527. //两个row的方向对应
  1528. let reversed = false
  1529. let lefts = [rowBigBox0.left, rowBigBox1.left]
  1530. let rights = [rowBigBox0.right, rowBigBox1.right]
  1531. let dis0 = lefts[0].btmPos.distanceToSquared(lefts[1].btmPos)
  1532. let dis1 = rights[0].btmPos.distanceToSquared(rights[1].btmPos)
  1533. let dis2 = lefts[0].btmPos.distanceToSquared(rights[1].btmPos)
  1534. let dis3 = rights[0].btmPos.distanceToSquared(lefts[1].btmPos)
  1535. let posLeft2, posRight2
  1536. if (dis0 + dis1 > dis2 + dis3) {
  1537. //距离近的代表是同一端
  1538. reversed = true
  1539. posLeft2 = new THREE.Vector3().addVectors(lefts[0].btmPos, rights[1].btmPos).multiplyScalar(0.5)
  1540. posRight2 = new THREE.Vector3().addVectors(rights[0].btmPos, lefts[1].btmPos).multiplyScalar(0.5)
  1541. } else {
  1542. posLeft2 = new THREE.Vector3().addVectors(lefts[0].btmPos, lefts[1].btmPos).multiplyScalar(0.5)
  1543. posRight2 = new THREE.Vector3().addVectors(rights[0].btmPos, rights[1].btmPos).multiplyScalar(0.5)
  1544. }
  1545. let vec = new THREE.Vector2(posLeft2.x - posRight2.x, posLeft2.z - posRight2.z)
  1546. let k = Math.abs(vec.x / vec.y) //这个算斜率更准,但位置容易偏向一侧(可能用边缘的bbox算会好些?)
  1547. return { reversed, k }
  1548. }
  1549. let searchByRow = (groups, datas) => {
  1550. //先查找row,匹配row,再slice row的方法
  1551. this.matchScoreMap['rowBigBox'] = {}
  1552. let rowInfos = []
  1553. let getRowMatchInfo = (rowBigBox0, rowBigBox1, ignoreCountMatch) => {
  1554. //获取row间的匹配信息
  1555. //获取bigBox位置。由于一排的盒子比较长,中心方向误差大,所以采用先获取两边位置,再求中点的方法
  1556. //if (rowBigBox0.boxes.length != rowBigBox1.boxes.length && !ignoreCountMatch) return //太难了,不算不一样的情况了
  1557. let name = rowBigBox0.sid + '&' + rowBigBox1.sid
  1558. if (name in rowInfos) {
  1559. return rowInfos[name]
  1560. }
  1561. if (name == 'pano4-row-2,11,10,8,6&pano6-row-2,5,8,11') {
  1562. console.log(3)
  1563. }
  1564. if (rowBigBox0.boxes.length != rowBigBox1.boxes.length && !ignoreCountMatch) return
  1565. //if (getBoxCount(rowBigBox0) != getBoxCount(rowBigBox1) && getBoxCount(rowBigBox0) != 1 && getBoxCount(rowBigBox1) != 1)return
  1566. /* if (rowBigBox0.sid == 'pano0-row-1,2,6' && rowBigBox1.sid == 'pano2-row-0,2,6') {
  1567. console.log(4)
  1568. } */
  1569. let rowInfo
  1570. if (rowBigBox0.boxes.length > 1 && rowBigBox1.boxes.length > 1) {
  1571. //多对多,可以求两端的位置
  1572. let lefts = [rowBigBox0.left, rowBigBox1.left]
  1573. let rights = [rowBigBox0.right, rowBigBox1.right]
  1574. let leftInfo
  1575. let rightInfo
  1576. let info2 = getReverseInfo(rowBigBox0, rowBigBox1)
  1577. let len0 = rowBigBox0.predictLen, //长度应该接近
  1578. len1 = rowBigBox1.predictLen
  1579. let overLen = Math.abs(len0 - len1) /* / (rowBigBox0.boxes.length + rowBigBox1.boxes.length) * 5 */
  1580. if (overLen > 1) {
  1581. //console.warn('overLen> 1', overLen, rowBigBox0.sid, '和', rowBigBox1.sid)
  1582. return done()
  1583. }
  1584. if (info2.reversed) {
  1585. leftInfo = getMatchScore(lefts[0], rights[1], { isSingle: true })
  1586. rightInfo = getMatchScore(rights[0], lefts[1], { isSingle: true })
  1587. } else {
  1588. leftInfo = getMatchScore(lefts[0], lefts[1], { isSingle: true })
  1589. rightInfo = getMatchScore(rights[0], rights[1], { isSingle: true })
  1590. }
  1591. let posLeft = getBoxPos(leftInfo)
  1592. let posRight = getBoxPos(rightInfo)
  1593. if (!posLeft || !posRight || leftInfo.score < -4000 || rightInfo.score < -4000) {
  1594. return done() //漫游点重合、>180度会导致此问题
  1595. }
  1596. preDealBox(leftInfo)
  1597. //getBoxSize(leftInfo)
  1598. preDealBox(rightInfo)
  1599. //getBoxSize(rightInfo)
  1600. posLeft = getBoxPos(leftInfo)
  1601. posRight = getBoxPos(rightInfo)
  1602. //验证是否是垂直或水平
  1603. let vec = new THREE.Vector2(posLeft.x - posRight.x, posLeft.z - posRight.z)
  1604. let k = Math.abs(vec.x / vec.y)
  1605. if ((info2.k > 1 && k < 1) || (info2.k < 1 && k > 1)) {
  1606. console.error('请检查!info2.k > 1 && k < 1 || info2.k < 1 && k > 1', rowBigBox0.sid, '和', rowBigBox1.sid) //绘制的方向错误,尺寸错误
  1607. return done()
  1608. }
  1609. let wrongK = 0
  1610. if ((rowBigBox0.k > 1 && rowBigBox1.k < 1) || (rowBigBox0.k < 1 && rowBigBox1.k > 1)) {
  1611. wrongK = rowBigBox0.k / rowBigBox1.k
  1612. if (wrongK < 1) wrongK = 1 / wrongK
  1613. }
  1614. /*
  1615. let trend0 = getPanoBoxAngleTrend(rowBigBox0)
  1616. let trend1 = getPanoBoxAngleTrend(rowBigBox1)
  1617. let judgeReverse = () => { //这个方法有时不准
  1618. let disLeftSquared0 = new THREE.Vector2(posLeft.x - rowBigBox0.pano.position.x, posLeft.z - rowBigBox0.pano.position.z).lengthSq()
  1619. let disRightSquared0 = new THREE.Vector2(posRight.x - rowBigBox0.pano.position.x, posRight.z - rowBigBox0.pano.position.z).lengthSq()
  1620. let a = trend0 * (disLeftSquared0 - disRightSquared0)
  1621. if (a < 0 && Math.abs(a) > 0.1) return true
  1622. let posLeft2 = reversed ? posRight : posLeft, //反向过的对第二个漫游点来说左右是反的
  1623. posRight2 = reversed ? posLeft : posRight
  1624. let disLeftSquared1 = new THREE.Vector2(posLeft2.x - rowBigBox1.pano.position.x, posLeft2.z - rowBigBox1.pano.position.z).lengthSq()
  1625. let disRightSquared1 = new THREE.Vector2(posRight2.x - rowBigBox1.pano.position.x, posRight2.z - rowBigBox1.pano.position.z).lengthSq()
  1626. let b = trend1 * (disLeftSquared1 - disRightSquared1)
  1627. if (b < 0 && Math.abs(b) > 0.1) return true
  1628. }
  1629. if (leftInfo.score < -2000 || rightInfo.score < -2000 || judgeReverse()) {
  1630. //反向试试
  1631. leftInfo = getMatchScore(lefts[0], rights[1], { isSingle: true })
  1632. rightInfo = getMatchScore(rights[0], lefts[1], { isSingle: true })
  1633. posLeft = getBoxPos(leftInfo)
  1634. posRight = getBoxPos(rightInfo)
  1635. reversed = true //rowBigBox1 反向了
  1636. }
  1637. if (leftInfo.score < -2000 || rightInfo.score < -2000 || judgeReverse()) {
  1638. return console.log('getCenter ;两个方向都不符合', rowBigBox0.sid, rowBigBox1.sid)
  1639. } */
  1640. /*const maxK = Math.max(0.6 / Math.sqrt(rowBigBox0.boxes.length), 0.2) // 最大斜率
  1641. if (k < maxK && k > 1 / maxK) {
  1642. return //console.log('放弃,斜率', k)
  1643. } */
  1644. //横的话,按x从小到大,竖的按z从小到大
  1645. if ((k < 1 && posLeft.z > posRight.z) || (k > 1 && posLeft.x > posRight.x)) {
  1646. let temp = posRight
  1647. ;(posRight = posLeft), (posLeft = temp)
  1648. }
  1649. //addLabel(posLeft, 'left-' + rowBigBox0.pano.id + '&' + rowBigBox1.pano.id, { a: 0.1 })
  1650. //addLabel(posRight, 'right-' + rowBigBox0.pano.id + '&' + rowBigBox1.pano.id, { a: 0.1 })
  1651. /* if (rowBigBox0.pano.id + '&' + rowBigBox1.pano.id == '22&26') {
  1652. console.log(777)
  1653. } */
  1654. /* var line1 = LineDraw.createLine([posLeft, posRight])
  1655. meshGroup.add(line1) */
  1656. //根据btmPos矫正一下中心位置, 否则容易偏漫游点这一侧
  1657. let center = new THREE.Vector3().addVectors(posLeft, posRight).multiplyScalar(0.5)
  1658. center
  1659. .add(rowBigBox0.btmPos)
  1660. .add(rowBigBox1.btmPos)
  1661. .multiplyScalar(1 / 3)
  1662. let axis = k > 1 ? 'z' : 'x'
  1663. //posLeft[axis] = center[axis], posRight[axis] = center[axis]
  1664. let match = getMatchScore(rowBigBox0, rowBigBox1, { isSingle: true, center }) //是否预先传送center ?
  1665. //rowInfo.minAngs = [leftInfo.minAng , rightInfo.minAng]
  1666. /* if (match.name == 'pano4-row-6,4,1,3&pano0-row-0,1,4,5') {
  1667. console.log(8)
  1668. } */
  1669. let sc = match.score - overLen * 1000 - wrongK * 100 + leftInfo.score + rightInfo.score
  1670. if (sc < -4000) {
  1671. //console.log('放弃,匹配分过低,可能不是一组', rowBigBox0.sid, '和', rowBigBox1.sid, sc)
  1672. return done()
  1673. }
  1674. //console.log('getcenter', rowBigBox0.sid, '和', rowBigBox1.sid, overLen, match.score + overLen * 1000 + leftInfo.score + rightInfo.score)
  1675. rowInfo = {
  1676. rowBigBox0,
  1677. rowBigBox1,
  1678. match,
  1679. k,
  1680. posLeft,
  1681. posRight,
  1682. score: sc / 3 + 500, //700 + match.score*0.7 + (leftInfo.score + rightInfo.score)*0.3 ,
  1683. reversed: info2.reversed,
  1684. }
  1685. } else {
  1686. if (rowBigBox0.boxes.length == 1 && rowBigBox1.boxes.length == 1) {
  1687. rowInfo = getMatchScore(rowBigBox0.boxes[0], rowBigBox1.boxes[0]) //直接匹配box
  1688. } else {
  1689. //一对多。getMatchScore计算误差大(长度越长中心误差越大、宽度计算也误差大)所以再写点限制。直接使用btm来预测长度和位置似乎更准
  1690. let mulBoxRow = rowBigBox0.boxes.length > 1 ? rowBigBox0 : rowBigBox1
  1691. let singleBox = rowBigBox0.boxes.length == 1 ? rowBigBox0 : rowBigBox1
  1692. /* if(rowBigBox0.sid == "pano12-row-3" && rowBigBox1.sid == "pano0-row-3,1,0" ){
  1693. console.log(5)
  1694. } */
  1695. rowInfo = getMatchScore(rowBigBox0, rowBigBox1, { dontCheckDis: true }) //一对多 也可以根据方向检查距离,如仅检查z
  1696. rowInfo.k = mulBoxRow.k
  1697. if (rowInfo.center) {
  1698. rowInfo.center.add(getBoxPos(mulBoxRow)).multiplyScalar(0.5)
  1699. }
  1700. if (rowInfo.name == 'pano0-row-14&pano4-row-8,11') {
  1701. addLabel(rowInfo.center, 'c')
  1702. }
  1703. rowInfo.predictSize = rowInfo.k > 1 ? { x: mulBoxRow.predictLen, y: 0.6 } : { y: mulBoxRow.predictLen, x: 0.6 }
  1704. //单个的应该和多个的其中一端一样,且是离单个漫游点近的那端(也就是要走到箱子一端看不见其他箱子才行)
  1705. let dis0 = getBoxPos(mulBoxRow.left).distanceToSquared(singleBox.pano.position)
  1706. let dis1 = getBoxPos(mulBoxRow.right).distanceToSquared(singleBox.pano.position)
  1707. let near = dis0 < dis1 ? mulBoxRow.left : mulBoxRow.right
  1708. let p0 = getBoxPos(singleBox)
  1709. let dis = getBoxPos(near).distanceToSquared(p0)
  1710. rowInfo.score -= dis * 1000
  1711. let p1 = getBoxPos(mulBoxRow)
  1712. let vec1 = new THREE.Vector2(p1.x - singleBox.pano.position.x, p1.z - singleBox.pano.position.z).normalize() //看向中心的方向
  1713. let vec2 = new THREE.Vector2(singleBox.centerDir.x, singleBox.centerDir.z).normalize()
  1714. rowInfo.score += (vec1.dot(vec2) - 1) * 1000 //同一个方向是最好
  1715. }
  1716. }
  1717. function done(rowInfo) {
  1718. rowInfo && rowInfos.push(rowInfo)
  1719. rowInfos[name] = rowInfo
  1720. }
  1721. done(rowInfo)
  1722. return rowInfo
  1723. }
  1724. let matchGroups = []
  1725. let allRelations = []
  1726. let getK = info => {
  1727. let k
  1728. if (info.left) {
  1729. let vec = new THREE.Vector2(info.left.x - info.right.x, info.left.z - info.right.z)
  1730. k = Math.abs(vec.x / vec.y)
  1731. } else {
  1732. k = Math.abs(Math.max(info.size.x, 0.6) / Math.max(info.size.z, 0.6))
  1733. }
  1734. return k
  1735. }
  1736. let ignoreCountMatch = groups.filter(e => e.length > 1).length == 1 //是否不同数量box的row也能匹配
  1737. let minScore = boundConfirmed ? -2000 : -800
  1738. let match = searchType => {
  1739. if (searchType == 'second') ignoreCountMatch = true
  1740. for (let i = 0; i < groups.length - 1; i++) {
  1741. let rowBigBoxes_0 = getPanoBigRowBox(groups[i])
  1742. let pano0 = groups[i][0].pano
  1743. if (searchType == 'second') rowBigBoxes_0 = rowBigBoxes_0.filter(e => !matchGroups.some(u => u.includes(e)))
  1744. for (let j = i + 1; j < groups.length; j++) {
  1745. let rowBigBoxes_1 = getPanoBigRowBox(groups[j])
  1746. if (searchType == 'second') rowBigBoxes_1 = rowBigBoxes_1.filter(e => !matchGroups.some(u => u.includes(e)))
  1747. let pano1 = groups[j][0].pano
  1748. let resultPairs = []
  1749. let bigBoxes_0, bigBoxes_1
  1750. if (rowBigBoxes_0.length < rowBigBoxes_1.length) {
  1751. bigBoxes_0 = rowBigBoxes_1.slice()
  1752. bigBoxes_1 = rowBigBoxes_0.slice()
  1753. } else {
  1754. bigBoxes_0 = rowBigBoxes_0.slice()
  1755. bigBoxes_1 = rowBigBoxes_1.slice()
  1756. }
  1757. while (bigBoxes_1.length < bigBoxes_0.length) {
  1758. bigBoxes_1.push({ sid: 'void' }) //为了使排列正确,补个空,使左右两边个数相等,过后和void匹配的不会计算box
  1759. }
  1760. if (!bigBoxes_0[0]) continue
  1761. searchPair(bigBoxes_0[0], bigBoxes_0, bigBoxes_1, null, resultPairs)
  1762. resultPairs = resultPairs.map(pairs => {
  1763. let infos = pairs.map(pair => (pair.some(e => e.sid == 'void') ? null : getRowMatchInfo(pair[0], pair[1], ignoreCountMatch)))
  1764. //infos.sort((a,b)=>{return a.score-b.score});
  1765. let score = infos.reduce((s, e) => {
  1766. return s + (e && e.score > minScore ? e.score : minScore / 2) //只考虑组成功的分数
  1767. }, 0)
  1768. return {
  1769. pairs,
  1770. infos,
  1771. score,
  1772. name: pairs.map(pair => pair.map(item => item.sid).join(' & ')),
  1773. }
  1774. })
  1775. resultPairs.sort((a, b) => b.score - a.score)
  1776. /* if (resultPairs[0].name[0].includes('pano8') && resultPairs[0].name[0].includes('pano0')) {
  1777. console.log(111)
  1778. } */
  1779. resultPairs[0].pairs.forEach((pair, i) => {
  1780. let info = resultPairs[0].infos[i]
  1781. if (info && info.score > minScore) {
  1782. allRelations.push(info)
  1783. let items = pair.filter(e => e.sid != 'void')
  1784. common.pushToGroupAuto(items, matchGroups, null, atGroup => {
  1785. //需要朝向一致才行
  1786. if (!info.k) return true //(box识别的宽高识别不准所以不需要)
  1787. let onePair = atGroup.relationships[0]
  1788. let name = onePair[0].sid + '&' + onePair[1].sid
  1789. if (!rowInfos[name].k) return true //不过不应该有这种情况,否则匹配不到一起才对
  1790. if ((rowInfos[name].k < 1 && info.k < 1) || (rowInfos[name].k > 1 && info.k > 1)) {
  1791. return true
  1792. } else {
  1793. console.log('k不一致无法匹配', info, atGroup)
  1794. }
  1795. })
  1796. //根据目前的规则应该是有端点的和有端点的匹配,box和box匹配
  1797. }
  1798. })
  1799. //console.log(resultPairs[0])
  1800. }
  1801. }
  1802. }
  1803. match()
  1804. ignoreCountMatch || match('second') //再次将剩余的匹配一下,这次允许个数不同的row匹配
  1805. console.log('matchGroups', matchGroups)
  1806. //识别出来的多组,可能有重复的,因为box个数不同所以才没到一组
  1807. //整理一下,每个组整理出一个info,同时重新检查一下,挑去每组中和其他成员非常不同的
  1808. let groupInfo = []
  1809. let getGroupInfo = group => {
  1810. let left = new THREE.Vector3(),
  1811. right = new THREE.Vector3(),
  1812. pointsLen = 0
  1813. let bigBoxes = []
  1814. let info = {}
  1815. group.relationships.forEach(pair => {
  1816. let name = pair[0].sid + '&' + pair[1].sid
  1817. let matchInfo = rowInfos[name] //this.matchScoreMap["rowBigBox"][name] || this.matchScoreMap["cabinet"][name];
  1818. if (matchInfo.posLeft) {
  1819. left.add(matchInfo.posLeft), right.add(matchInfo.posRight), pointsLen++
  1820. } else {
  1821. bigBoxes.push(matchInfo)
  1822. preDealBox(matchInfo)
  1823. getBoxSize(matchInfo)
  1824. }
  1825. })
  1826. let index = groupInfo.length
  1827. if (pointsLen > 0) {
  1828. left.multiplyScalar(1 / pointsLen)
  1829. right.multiplyScalar(1 / pointsLen)
  1830. //addLabel(left, 'Left' + index, { bgcolor: '#F00', a: 0.2 })
  1831. //addLabel(right, 'Right' + index, { bgcolor: '#F00', a: 0.2 })
  1832. let center = new THREE.Vector3().addVectors(left, right).multiplyScalar(0.5)
  1833. //addLabel(center, 'center' + index, { bgcolor: '#F00', a: 0.3 })
  1834. ;(info.left = left), (info.right = right), (info.center = center)
  1835. info.pointsLen = pointsLen
  1836. }
  1837. if (bigBoxes.length > 0) {
  1838. let getAve = bigBoxes => {
  1839. let center1 = new THREE.Vector3(),
  1840. size = new THREE.Vector3()
  1841. bigBoxes.forEach(box => {
  1842. let center0 = getBoxPos(box)
  1843. center1.add(center0)
  1844. size.add(box.size)
  1845. })
  1846. if (pointsLen > 0) {
  1847. let size0 = new THREE.Vector3(Math.abs(left.x - right.x), size.y, Math.abs(left.z - right.z))
  1848. size.add(size0.multiplyScalar(pointsLen)).multiplyScalar(1 / (pointsLen + bigBoxes.length))
  1849. center1.add(info.center.clone().multiplyScalar(pointsLen)).multiplyScalar(1 / (pointsLen + bigBoxes.length))
  1850. } else {
  1851. size.multiplyScalar(1 / bigBoxes.length)
  1852. center1.multiplyScalar(1 / bigBoxes.length)
  1853. }
  1854. return { center1, size }
  1855. }
  1856. let getScores = (center, size) => {
  1857. //获得相对于center,size的差别分数
  1858. bigBoxes.forEach(box => {
  1859. box.sc = -box.center.distanceToSquared(center1) - size.distanceToSquared(box.size) * 0.5
  1860. })
  1861. }
  1862. let { center1, size } = getAve(bigBoxes)
  1863. //console.log(center1, size)
  1864. getScores(center1, size)
  1865. bigBoxes.sort((a, b) => b.sc - a.sc)
  1866. let midItem = bigBoxes[Math.floor(bigBoxes.length / 2)] //中位数
  1867. getScores(midItem.center, midItem.size)
  1868. const minScore = -8
  1869. let removes = bigBoxes.filter(e => {
  1870. return e.sc < minScore
  1871. })
  1872. if (removes.length) {
  1873. let { newGroups } = common.disconnectGroup(
  1874. removes.map(e => [e.box0, e.box1]),
  1875. matchGroups
  1876. )
  1877. console.log('去除错误数据', removes)
  1878. if (newGroups.length > 1) {
  1879. //分裂成多组了,重新计算
  1880. newGroups.forEach(e => {
  1881. getGroupInfo(e)
  1882. })
  1883. return
  1884. }
  1885. bigBoxes = bigBoxes.filter(e => {
  1886. return e.sc >= minScore
  1887. })
  1888. }
  1889. if (bigBoxes.length) {
  1890. let o = getAve(bigBoxes) //again
  1891. ;(info.center = o.center1), (info.size = o.size)
  1892. }
  1893. }
  1894. info.k = getK(info)
  1895. info.bigBoxes = bigBoxes
  1896. info.group = group
  1897. groupInfo.push(info)
  1898. }
  1899. matchGroups.slice(0).forEach(group => {
  1900. getGroupInfo(group)
  1901. })
  1902. let getLength = c => {
  1903. //获取bigbox长度
  1904. return c.size ? (c.k > 1 ? c.size.x : c.size.z) : c.k > 1 ? c.right.x - c.left.x : c.right.z - c.left.z + 0.6
  1905. }
  1906. let getLeft = (group, k) => {
  1907. let dirAxis = (k || group.k) > 1 ? 'x' : 'z'
  1908. return group.left ? group.left[dirAxis] - 0.3 : group.center[dirAxis] - group.size[dirAxis] / 2 //left和right加减半个宽度
  1909. }
  1910. let getRight = (group, k) => {
  1911. let dirAxis = (k || group.k) > 1 ? 'x' : 'z'
  1912. return group.right ? group.right[dirAxis] + 0.3 : group.center[dirAxis] + group.size[dirAxis] / 2
  1913. }
  1914. //识别是否group之间有一样的, 去重
  1915. {
  1916. let realGroups = []
  1917. let getAveWidth = (infos, len) => {
  1918. //获取这些infos最合适的箱子平均宽度和个数
  1919. let boxCounts = []
  1920. infos.forEach(e => {
  1921. boxCounts.push(...e.group.map(bigBox => bigBox.boxes.length))
  1922. })
  1923. boxCounts.sort((a, b) => a - b)
  1924. let midCounts = []
  1925. let r0 = 0.3,
  1926. r1 = 0.7 //取中间这部分的算最适合的个数,结果不一定是中位数
  1927. boxCounts.slice(Math.floor(boxCounts.length * r0), Math.floor(boxCounts.length * r1) + 1).forEach(c => {
  1928. if (!midCounts.includes(c)) midCounts.push(c)
  1929. })
  1930. let { min, max } = standards.cabinet.widthNormal
  1931. let standardW = (min + max) / 2
  1932. let aveWs = midCounts.map(e => {
  1933. return { aveW: len / e, count: e }
  1934. })
  1935. aveWs.sort((a, b) => Math.abs(a.aveW - standardW) - Math.abs(b.aveW - standardW))
  1936. let aveW = aveWs[0].aveW
  1937. let count = aveWs[0].count
  1938. if (aveW > max || aveW < min) {
  1939. let w = THREE.MathUtils.clamp(aveW, min, max)
  1940. //console.warn(`box aveW宽度不太对,从${aveW}修改到${w}`)
  1941. aveW = w
  1942. }
  1943. return { aveW, count }
  1944. }
  1945. let getBox2 = (center, len, thick, k) => {
  1946. let box2 = new THREE.Box2()
  1947. box2.expandByPoint(new THREE.Vector2(center.x, center.z))
  1948. let sizeVec = k > 1 ? new THREE.Vector2(len / 2, thick / 2) : new THREE.Vector2(thick / 2, len / 2)
  1949. box2.expandByVector(sizeVec)
  1950. return box2
  1951. }
  1952. const standardW = 0.6 //两排之间最小距离
  1953. for (let m = 0; m < groupInfo.length - 1; m++) {
  1954. let group0 = groupInfo[m]
  1955. for (let n = m + 1; n < groupInfo.length; n++) {
  1956. let group1 = groupInfo[n]
  1957. if (group1.bigBoxes[0]?.name == 'pano4-row-4&pano6-row-5,1' && group0.bigBoxes[0]?.name == 'pano4-row-2,5&pano6-row-3') {
  1958. console.log(4)
  1959. }
  1960. /* if (group0.k == 4.242560016595383 || group1.k == 0.8571428571428572) {
  1961. console.log(2)
  1962. } */
  1963. const maxR = 2.3
  1964. if (((group0.k > 1 && group1.k < 1) || (group0.k < 1 && group1.k > 1)) && getLength(group0) > 1.5 && getLength(group1) > 1.5) continue //如果是方块状的无视k
  1965. //间距
  1966. let spaceAxis = (group0.k + group1.k) / 2 > 1 ? 'z' : 'x'
  1967. let spaceDis = Math.abs(group0.center[spaceAxis] - group1.center[spaceAxis])
  1968. if (spaceDis > standardW * 1.5) continue
  1969. let o0 = getAveWidth([group0], getLength(group0)) //因为有可能长度和箱子个数不匹配,所以需要得到限制后的宽度再比较
  1970. let o1 = getAveWidth([group1], getLength(group1))
  1971. let len0 = (group0.predictLen = o0.aveW * o0.count)
  1972. let len1 = (group1.predictLen = o1.aveW * o1.count)
  1973. const minR = 0.5 //不可限制太死,因为有的框个数识别少了,导致len短。但可通过重叠面积来判断
  1974. // if( len0 / len1 < minR || len0 / len1 > 1/minR) continue
  1975. let area0 = (group0.area = len0 * o0.aveW)
  1976. let area1 = (group1.area = len1 * o1.aveW)
  1977. let getBoxMixArea = (expandRatio1, expandRatio2) => {
  1978. let box0 = getBox2(group0.center, len0 + expandRatio1, o0.aveW + expandRatio2, group0.k)
  1979. let box1 = getBox2(group1.center, len1 + expandRatio1, o1.aveW + expandRatio2, group1.k)
  1980. let mixBox = getMixBox(box0, box1) //重叠部分
  1981. let s = mixBox.getSize(new THREE.Vector2())
  1982. return { box0, box1, areaMix: Math.max(0, s.x) * Math.max(0, s.y) } //可能是0
  1983. }
  1984. let areaMixExpand = getBoxMixArea(0.1, 0.3).areaMix
  1985. if (areaMixExpand / area0 < 0.65 && areaMixExpand / area1 < 0.65) continue //包含的可以通过
  1986. /*let areaMix = getBoxMixArea(0, 0).areaMix //实际重合面积
  1987. group0.contains = group0.contains || []
  1988. group1.contains = group1.contains || []
  1989. group0.contains.push({ group: group1, selfPercent: areaMix / area0, percent2: areaMix / area1, areaMix })
  1990. group1.contains.push({ group: group0, selfPercent: areaMix / area1, percent2: areaMix / area0, areaMix })
  1991. */
  1992. //console.log('两个合并', group0, group1)
  1993. common.pushToGroupAuto([group0, group1], realGroups)
  1994. //包含的直接合并吧 - - ,这样会使结果偏移,不过没办法了,多个重叠面积太难算了
  1995. }
  1996. }
  1997. //但没合并前样本数量少,包含关系可能有错 - -
  1998. /*for(let m=0; m<groupInfo.length;m++){
  1999. let group = groupInfo[m]
  2000. let contains = group.contains.filter(e=> e.percent2 > 0.8) //所有包含的
  2001. contains.reduce
  2002. } */
  2003. groupInfo.forEach(info => {
  2004. //加入单个的
  2005. if (!realGroups.some(groups => groups.includes(info))) {
  2006. realGroups.push([info])
  2007. }
  2008. })
  2009. console.log('realGroups', realGroups)
  2010. //get boxes
  2011. realGroups.forEach((infos, i) => {
  2012. const sampleCount = infos.reduce((w, c) => {
  2013. return (w += c.pointsLen || c.bigBoxes.length)
  2014. }, 0)
  2015. let k
  2016. /* {
  2017. //const k = infos.reduce((w, c) => (w += c.k), 0) / infos.length
  2018. let ks = infos.map(e => e.k)
  2019. ks.sort((a, b) => a - b)
  2020. let min = ks[0],
  2021. max = ks[ks.length - 1]
  2022. if (min < 1 && max > 1) {
  2023. //比较最小和最大,选取更极端的那个
  2024. let min_ = 1 / min
  2025. if (min_ < max) k = max
  2026. else k = min
  2027. } else k = (min + max) / 2
  2028. } */
  2029. {
  2030. //看>1的和<1的平均数哪个多用哪个
  2031. let ks = { '<1': { count: 0, sum: 0 }, '>1': { count: 0, sum: 0 } }
  2032. infos.forEach(e => {
  2033. if (e.k < 1) {
  2034. ks['<1'].count++, (ks['<1'].sum += 1 / e.k)
  2035. } else {
  2036. ks['>1'].count++, (ks['>1'].sum += e.k)
  2037. }
  2038. })
  2039. ks['<1'].count && (ks['<1'].ave = ks['<1'].sum / ks['<1'].count)
  2040. ks['>1'].count && (ks['>1'].ave = ks['>1'].sum / ks['>1'].count)
  2041. if (ks['<1'].ave > ks['>1'].ave) {
  2042. k = 1 / ks['<1'].ave
  2043. } else {
  2044. k = ks['>1'].ave
  2045. }
  2046. }
  2047. let centerPos = infos
  2048. .reduce((w, c) => {
  2049. return w.add(c.center.clone().multiplyScalar(c.pointsLen || c.bigBoxes.length))
  2050. }, new THREE.Vector3())
  2051. .multiplyScalar(1 / sampleCount) //预得中心点
  2052. //获取左右端点(需要排除可能的误差,所以采用最靠近端点的三个点。但无法排除前三个点中万一含有包含box的、或者误差大的端点)
  2053. let lefts = infos
  2054. .map(e => getLeft(e, k))
  2055. .sort((a, b) => a - b)
  2056. .filter(a => a < centerPos[k > 1 ? 'x' : 'z'])
  2057. .slice(0, 3)
  2058. let rights = infos
  2059. .map(e => getRight(e, k))
  2060. .sort((a, b) => b - a)
  2061. .filter(a => a > centerPos[k > 1 ? 'x' : 'z'])
  2062. .slice(0, 3)
  2063. let left = 0,
  2064. right = 0
  2065. let c0 = ((lefts.length + 1) * lefts.length) / 2
  2066. lefts.forEach((e, i) => {
  2067. //越靠近最外侧权重越高。
  2068. left += e * ((lefts.length - i) / c0)
  2069. })
  2070. c0 = ((rights.length + 1) * rights.length) / 2
  2071. rights.forEach((e, i) => {
  2072. right += e * ((rights.length - i) / c0)
  2073. })
  2074. centerPos[k > 1 ? 'x' : 'z'] = (left + right) / 2
  2075. let len = right - left //加一点值是因为之前计算长度,用的是最外box的中心点,会少box一半宽度
  2076. let infos2 = infos.filter(e => {
  2077. return !e.predictLen || e.predictLen / len > 0.7
  2078. })
  2079. if (infos2.length == 0) {
  2080. infos2 = infos.sort((a, b) => b.predictLen - a.predictLen).slice(0, 1)
  2081. }
  2082. let { aveW, count } = getAveWidth(infos2, len)
  2083. //长宽比中心点的误差更大,尤其是box类型的、或样本少的
  2084. //获取高度
  2085. let heights = []
  2086. {
  2087. let pairs = [],
  2088. heightss
  2089. /* infos.forEach(e => {
  2090. pairs.push(...e.group.relationships.filter(pair => pair[0].boxes.length == count && pair[1].boxes.length == count))
  2091. })
  2092. if (pairs.length) {
  2093. heightss = pairs.map(pair => {
  2094. let boxes = pair.map(e => {
  2095. return e.boxes.slice()
  2096. })
  2097. let match = rowInfos[pair[0].sid + '&' + pair[1].sid]
  2098. let ifReverse = match.reversed
  2099. if (match.reversed == void 0 && pair[0].boxes.length > 1 && pair[1].boxes.length > 1) {
  2100. let { reversed } = getReverseInfo(pair[0], pair[1])
  2101. ifReverse = reversed
  2102. }
  2103. if (ifReverse) {
  2104. boxes[1].reverse()
  2105. }
  2106. let heights1 = []
  2107. let topPoss = []
  2108. for (let i = 0; i < count; i++) {
  2109. let match1 = getMatchScore(boxes[0][i], boxes[1][i], { onlyGet: true })
  2110. let topPos = match1 && match1.topPos
  2111. if (!topPos) {
  2112. topPos = getBoxTop({ box0: boxes[0][i], box1: boxes[1][i] })
  2113. }
  2114. heights1.push(topPos.y - groundY)
  2115. if (topPos.y - groundY < 0) {
  2116. console.log('?')
  2117. }
  2118. topPoss.push(topPos)
  2119. }
  2120. if ((k < 1 && topPoss[0].z > topPoss[count - 1].z) || (k > 1 && topPoss[0].x > topPoss[count - 1].x)) {
  2121. heights1.reverse()
  2122. }
  2123. return heights1
  2124. })
  2125. } else { */
  2126. let bigBoxes = []
  2127. infos.forEach(e => {
  2128. bigBoxes.push(...e.group.filter(e => !bigBoxes.includes(e) && e.boxes.length == count))
  2129. })
  2130. heightss = bigBoxes.map(bigBox => {
  2131. let topPoss = bigBox.boxes.map(box => {
  2132. let a = { box0: box }
  2133. getBoxTop(a)
  2134. return a.topPos
  2135. })
  2136. if ((k < 1 && topPoss[0].z > topPoss[count - 1].z) || (k > 1 && topPoss[0].x > topPoss[count - 1].x)) {
  2137. topPoss.reverse()
  2138. }
  2139. let heights1 = topPoss.map(topPos => topPos.y - groundY)
  2140. return heights1
  2141. })
  2142. //}
  2143. heightss.forEach(arr => {
  2144. for (let i = 0; i < count; i++) {
  2145. heights[i] = (heights[i] || 0) + arr[i]
  2146. }
  2147. })
  2148. heights = heights.map(e => {
  2149. let h = e / heightss.length
  2150. return h
  2151. })
  2152. //console.log('heightss',heightss, pairs, heights)
  2153. }
  2154. //拆分成小box
  2155. let size = new THREE.Vector3(aveW, 2, aveW)
  2156. let c = 0
  2157. infos.box = []
  2158. while (c < count) {
  2159. let center
  2160. if (k > 1) {
  2161. let startX = centerPos.x - ((count - 1) / 2) * aveW
  2162. center = new THREE.Vector3(startX + c * aveW, centerPos.y, centerPos.z)
  2163. } else {
  2164. let startZ = centerPos.z - ((count - 1) / 2) * aveW
  2165. center = new THREE.Vector3(centerPos.x, centerPos.y, startZ + c * aveW)
  2166. }
  2167. let size1 = heights[c] ? size.clone().setY(heights[c]) : size //如1*3的是得不到height的
  2168. let box = new Box({ name: 'row' + i + '-' + c, center, size: size1, boxType: 'cabinet', infos })
  2169. c++
  2170. infos.box.push(box)
  2171. }
  2172. })
  2173. return realGroups.length > 0
  2174. }
  2175. }
  2176. let removeContain = arr => {
  2177. //去除嵌套
  2178. let len = arr.length
  2179. if (len < 2) return
  2180. for (let i = 0; i < len - 1; i++) {
  2181. let box0 = arr[i]
  2182. getBoxBase(box0)
  2183. box0.contains = box0.contains || []
  2184. for (let j = i + 1; j < len; j++) {
  2185. let box1 = arr[j]
  2186. if (box0.sid == 'pano2-1' && box1.sid == 'pano2-7') {
  2187. console.log(6)
  2188. }
  2189. getBoxBase(box1)
  2190. box1.contains = box1.contains || []
  2191. let d3 = Math.abs(box1.bbox2CenterX - box0.bbox2CenterX) //限制d3是因为在相差180度两端可能也符合
  2192. //d4 = Math.abs(box1.bbox2[3] - box0.bbox2[3])
  2193. if (d3 > 0.4 /* || d4 > 0.01 */) continue
  2194. let d0 = getBbox2Diff(box1.bbox2[0], box0.bbox2[0]),
  2195. d1 = getBbox2Diff(box0.bbox2[2], box1.bbox2[2]),
  2196. w0 = getBbox2Diff(box0.bbox2[2], box0.bbox2[0]),
  2197. w1 = getBbox2Diff(box1.bbox2[2], box1.bbox2[0])
  2198. let min = Math.min(0.005, Math.min(w0, w1) * 0.2) //如果本身w0,w1宽度就小,差距更要小
  2199. if ((d1 >= 0 && Math.abs(d0) < min) || (d0 >= 0 && Math.abs(d1) < min) || (d1 >= 0 && d0 >= 0)) {
  2200. box0.contains.push(box1)
  2201. } else if ((d0 <= 0 && Math.abs(d1) < min) || (d1 <= 0 && Math.abs(d0) < min) || (d1 <= 0 && d0 <= 0)) {
  2202. box1.contains.push(box0)
  2203. }
  2204. }
  2205. }
  2206. let getWidthScore = (box, type) => {
  2207. const addDis = 0.1 //因为用的是btm的pos,比中心点近了一些,所以加上一段距离
  2208. let o = getBoxPoseByPos(box, getBoxPos(box), addDis)
  2209. let boxPjW = o.projectWidth
  2210. let standardPjW = (o.maxProjectWidth + o.minProjectWidth) / 2
  2211. let s = type == 'out' ? boxPjW - standardPjW : standardPjW - boxPjW
  2212. return -Math.pow(s, 2) * 10
  2213. }
  2214. let minChildCount = arr[0].boxType == 'battery' ? 1 : 2
  2215. arr.slice().forEach(box => {
  2216. if (box.contains.length >= minChildCount) {
  2217. //假设不存在第二层嵌套, 假设每个只能被一个嵌套
  2218. //决定留大还是留小
  2219. //先只去掉包含两个以上的,且角度范围一致
  2220. //尽量保留内层,除非内层太小
  2221. let { leftX, rightX } = getLeftRight(box.contains)
  2222. if (box.contains.length > 1 && (Math.abs(getBbox2Diff(box.bbox2[0], leftX)) > 0.005 || Math.abs(getBbox2Diff(box.bbox2[2], rightX)) > 0.005)) return //范围不一致
  2223. let remainChild = true
  2224. if (box.contains.length == 1) {
  2225. //cdi6xzNiNdS 电池包含单个 感觉一般都是留大
  2226. remainChild = false
  2227. } else {
  2228. let outScore = getWidthScore(box, 'out')
  2229. let childrenScores = box.contains.map(e => getWidthScore(e, 'in'))
  2230. let childAve = childrenScores.reduce((w, c) => w + c, 0) / childrenScores.length
  2231. if (childAve < -4) {
  2232. //let outScore = getWidthScore(box, 'out')
  2233. remainChild = childAve > outScore
  2234. }
  2235. }
  2236. if (!remainChild) {
  2237. box.contains.forEach(e => {
  2238. ;(e.state = '因被嵌套被删除'), (e.containBy = box)
  2239. arr.splice(arr.indexOf(e), 1)
  2240. console.log('因被嵌套被删除', ...box.contains)
  2241. })
  2242. } else {
  2243. box.state = '因嵌套其他被删除'
  2244. console.log('因嵌套其他被删除', box)
  2245. arr.splice(arr.indexOf(box), 1)
  2246. }
  2247. }
  2248. })
  2249. }
  2250. let waitFindRest = []
  2251. let Search = type => {
  2252. console.error('开始search', type)
  2253. let matchScoreMap = (this.matchScoreMap[type] = {})
  2254. let datas = {}
  2255. let panoIds = []
  2256. for (let id in this.datas) {
  2257. if(!this.datas[id])continue
  2258. datas[id] = this.datas[id].shapes.filter(e => isType(e, type))
  2259. datas[id].length && panoIds.push(id)
  2260. }
  2261. for (let id in this.datas) {
  2262. //对data预处理
  2263. //(之后如果还出现不同类型重叠在一起的,需要先识别摘除下。 )4GqaqNdyjGf
  2264. if(!this.datas[id])continue
  2265. removeContain(datas[id]) //去除线框中的嵌套,主要是一个嵌套两个的。案例:KK-1Zjm9Rbl47
  2266. if (datas[id].length) {
  2267. //融合。很多box被一分为二了,基本都是在全景图左右边界处。
  2268. let bigBoxes = getPanoBigRowBox(datas[id], { reason: 'mix' })
  2269. bigBoxes.forEach(bigBox => {
  2270. if (bigBox.boxes.length > 1) {
  2271. bigBox.boxes.forEach(box => {
  2272. ;(box.state = '被删除'), (box.mixTo = bigBox)
  2273. let i = datas[id].indexOf(box)
  2274. datas[id].splice(i, 1)
  2275. if (version == 'vision') {
  2276. i = this.datasMixed[id].shapes.findIndex(e => e.sid == box.sid)
  2277. this.datasMixed[id].shapes.splice(i, 1)
  2278. }
  2279. })
  2280. //console.log('因融合而删除', bigBox.boxes)
  2281. datas[id].push(bigBox)
  2282. if (version == 'vision') {
  2283. this.datasMixed[id].shapes.push(bigBox)
  2284. }
  2285. let shapes = this.datas[id].shapes
  2286. bigBox.index = shapes.length > 1 ? shapes[shapes.length - 2].index + 1 : 0
  2287. {
  2288. let a = bigBox.sid.split('mix-')
  2289. bigBox.sid = a[0] + bigBox.index + '(mix' + a[1] + ')' //"pano20-mix-1,2"
  2290. }
  2291. }
  2292. })
  2293. }
  2294. }
  2295. if (panoIds.length == 0) {
  2296. if (standards[type].tinyXZ) {
  2297. //fire 调试:nZrBdvRaDuC
  2298. this.expandModelBound()
  2299. }
  2300. return
  2301. }
  2302. panoIds.sort((a, b) => {
  2303. return datas[b].length - datas[a].length
  2304. })
  2305. let groups = panoIds.map(e => datas[e])
  2306. console.log('按box个数排序:', groups.slice())
  2307. let group0 = groups[0],
  2308. len0 = group0.length
  2309. if (groups.length == 1) {
  2310. //只有一个全景里有数据
  2311. if (standards[type].tinyXZ) {
  2312. //fire. 无法match以获取groundY, 就取消。 调试: eGhyf5QdVHA
  2313. this.expandModelBound(type)
  2314. }
  2315. group0.forEach(e => createSinglePano(e))
  2316. return combines(type)
  2317. }
  2318. let finish = groups => {
  2319. waitFindRest.push({ type, args: [groups] }) //等待最后检查遗漏
  2320. if (standards[type].tinyXZ) {
  2321. //fire 调试:nZrBdvRaDuC
  2322. this.confirmGroundY(type)
  2323. }
  2324. if (standards[type].tiny) {
  2325. //monitor 调试:S9yepREK8Jl
  2326. this.expandModelBound2(type)
  2327. }
  2328. }
  2329. if (len0 == 1) {
  2330. //最多的也只有一个box。此情况大部分是空调
  2331. panoIds.forEach(e => getBoxBase(datas[e][0]))
  2332. let maxAngle
  2333. //找出centerDir夹角最大的两个pano
  2334. for (let i = 0; i < panoIds.length; i++) {
  2335. let box0 = datas[panoIds[i]][0]
  2336. for (let j = i + 1; j < panoIds.length; j++) {
  2337. let box1 = datas[panoIds[j]][0]
  2338. getMatchScore(box0, box1, { isSingle: true })
  2339. }
  2340. }
  2341. let list = Object.keys(matchScoreMap)
  2342. list.sort((a, b) => {
  2343. return matchScoreMap[b].score - matchScoreMap[a].score
  2344. })
  2345. let match = matchScoreMap[list[0]]
  2346. preDealBox(match)
  2347. if (match.score > -100) {
  2348. getBoxSize(match)
  2349. if (match.score > 0 && match.sizeAdjust < 0.1) {
  2350. new Box(matchScoreMap[list[0]])
  2351. //waitFindRest.push({ type, args: [groups] }) //等待最后检查遗漏
  2352. finish(groups)
  2353. return
  2354. }
  2355. }
  2356. //根据分数重排序,前两个已匹配的pano放在第一第二(reMatchLowScores会跳过),获得groups2
  2357. let panoIds2 = []
  2358. list.forEach(e => {
  2359. let info = matchScoreMap[e]
  2360. if (!panoIds2.includes(info.box0.pano.id)) panoIds2.push(info.box0.pano.id)
  2361. if (!panoIds2.includes(info.box1.pano.id)) panoIds2.push(info.box1.pano.id)
  2362. })
  2363. let groups2 = panoIds2.map(e => datas[e])
  2364. //继续match
  2365. reMatchLowScores([match], groups2)
  2366. finish(groups2)
  2367. return
  2368. }
  2369. {
  2370. //重新根据距离排序,挑选离所有box距离最近的两个pano (远的可能看不到box,或者得到的线框计算的位置不准。不过其实太近也不准-,-)
  2371. let counts = {}
  2372. groups.forEach(e => {
  2373. e.forEach(a => getBoxBase(a))
  2374. counts[e.length] || (counts[e.length] = [])
  2375. counts[e.length].push(e)
  2376. })
  2377. groups = []
  2378. let atWall = standards[type].atWall
  2379. let nums = Object.keys(counts)
  2380. let bestDisSquared = 2
  2381. nums.reverse()
  2382. nums.forEach(count => {
  2383. let groups_ = counts[count]
  2384. if (groups_.length > 1) {
  2385. groups_.forEach(e => {
  2386. e.disSc = e.reduce((w, c) => {
  2387. let pos = getBoxPos(c)
  2388. //let s = atWall ? Math.pow(Math.abs(c.centerDir.y), 3)*100 : 0 //在墙上的话尽量平视
  2389. //console.log(c.sid,s)
  2390. return w + Math.abs(c.pano.position.distanceToSquared(pos) - bestDisSquared) //+ s
  2391. }, 0)
  2392. })
  2393. groups_.sort((a, b) => a.disSc - b.disSc)
  2394. }
  2395. groups.push(...groups_)
  2396. })
  2397. console.log('按距离和个数排序:', groups)
  2398. group0 = groups[0]
  2399. len0 = group0.length
  2400. }
  2401. if (type == 'cabinet') {
  2402. //转化为分组
  2403. if (searchByRow(groups, datas)) {
  2404. waitFindRest.push({ type, args: [groups, 0] }) //等待最后检查遗漏
  2405. return
  2406. }
  2407. }
  2408. //零散匹配。
  2409. let match2Group = (group0, group1, { fake }) => {
  2410. let len0 = group0.length,
  2411. len1 = group1.length
  2412. for (let i = 0; i < len0; i++) {
  2413. //复杂度:n的平方次
  2414. for (let j = 0; j < len1; j++) {
  2415. let box1 = group0[i]
  2416. let box2 = group1[j]
  2417. let result = getMatchScore(box1, box2)
  2418. }
  2419. }
  2420. //寻找最佳配对 n!种组合(是否要限制个数多的情况?) 超过8个就很恐怖
  2421. //仅先查找选中的两个pano配对
  2422. let resultPairs = []
  2423. let newGroup0 = group0.slice(0)
  2424. let newGroup1 = group1.slice(0)
  2425. while (newGroup1.length < newGroup0.length) {
  2426. newGroup1.push({ sid: 'void' }) //为了使排列正确,补个空,使左右两边个数相等,过后和void匹配的不会计算box
  2427. }
  2428. searchPair(group0[0], newGroup0, newGroup1, null, resultPairs)
  2429. /* console.log(
  2430. 'resultPairs',
  2431. resultPairs.map(pairs => pairs.map(pair => pair.map(item => item.sid).join(' & ')))
  2432. ) */
  2433. resultPairs = resultPairs.map(pairs => {
  2434. let infos = pairs.map(pair => matchScoreMap[pair[0].sid + '&' + pair[1].sid])
  2435. let score = infos.reduce((s, e) => {
  2436. return s + (e ? e.score : 0)
  2437. }, 0)
  2438. let o = {
  2439. infos,
  2440. score,
  2441. pairs,
  2442. name: pairs.map(pair => pair.map(item => item.sid).join(' & ')),
  2443. }
  2444. return o
  2445. })
  2446. //console.log('resultPairs', resultPairs.slice())
  2447. console.log(
  2448. 'resultPairs按分数高低',
  2449. resultPairs.sort((a, b) => b.score - a.score)
  2450. )
  2451. //console.log('compu',compu)
  2452. let minScore = boundConfirmed ? -2000 : -800
  2453. let noMatches = [] //和void匹配的,需要和其他pano的重新匹配
  2454. let mayHaventMatched = []
  2455. let lowScores = []
  2456. if (resultPairs[0]) {
  2457. resultPairs[0].infos.forEach((info, i) => {
  2458. if (!info) {
  2459. noMatches.push(resultPairs[0].pairs[i].find(e => e.sid != 'void'))
  2460. return //match with void
  2461. }
  2462. if (info.score < minScore || (standards[info.boxType].bottom && info.minAng < 5)) {
  2463. lowScores.push(info)
  2464. return
  2465. }
  2466. preDealBox(info)
  2467. getBoxSize(info)
  2468. if ((info.sizeAdjust && standards[info.boxType].tiny) || info.sizeAdjust > 0.2) {
  2469. //或者识别下悬挂的且线的角度较小
  2470. lowScores.push(info)
  2471. return
  2472. }
  2473. if (info.box0.category == typeNames.battery && info.size.x < 1 && info.size.z < 1) {
  2474. //宽度较小
  2475. let vec0 = new THREE.Vector3().subVectors(info.box0.pano.position, getBoxPos(info))
  2476. let vec1 = new THREE.Vector3().subVectors(info.box1.pano.position, getBoxPos(info))
  2477. /* let k0 = Math.abs(vec0.x / vec0.z), k1 = Math.abs(vec1.x / vec1.z), maxR = 6
  2478. if(info.name == '') */
  2479. if (vec0.x * vec1.x > 0 && vec0.z * vec1.z > 0 /* || k0/k1 > maxR || k0/k1 < 1/maxR */) {
  2480. //同一个象限 或 偏向一侧
  2481. lowScores.push(info)
  2482. return
  2483. }
  2484. }
  2485. info.fake = fake
  2486. let box = new Box(info)
  2487. })
  2488. }
  2489. if (noMatches.length) {
  2490. reMatchLowScores(
  2491. noMatches.map(e => {
  2492. return { box0: e }
  2493. }),
  2494. groups,
  2495. { fake }
  2496. )
  2497. }
  2498. reMatchLowScores(lowScores, groups, { fake })
  2499. }
  2500. {
  2501. for (let i = 0; i < groups.length - 1; i++) {
  2502. match2Group(groups[i], groups[i + 1], { fake: i > 0 })
  2503. if (!standards[type].tinyXZ /* && !browser.urlHasValue('many') */ || groups[i + 1].length < 2) {
  2504. break
  2505. }
  2506. }
  2507. }
  2508. finish(groups)
  2509. }
  2510. function blocked(box) {
  2511. //该box是否被实体box遮挡
  2512. //WcLVXvmV9AU:pano2-2 和 pano12-4 ; 5yhlMduTHL8:pano2-10
  2513. /* if (box.sid == 'pano6-7') {
  2514. console.log(1)
  2515. addLine(box.pano.position, box.centerBtmDir, 20)
  2516. } */
  2517. if (!standards[box.boxType].bottom) {
  2518. //当底部每个方向都有遮挡物时,其位置很可能不准。但若是部分遮住,还是有可能识别对的
  2519. if (!box.blocked) {
  2520. box.blocked = {
  2521. centerBtmDir: null,
  2522. leftBtmDir: null,
  2523. rightBtmDir: null,
  2524. }
  2525. }
  2526. for (let dir in box.blocked) {
  2527. if (!box.blocked[dir]) {
  2528. let block = boxesSolid.find(boxSolid => {
  2529. ray.set(box.pano.position, box[dir])
  2530. let o = ray.ray.intersectsBox(boxSolid.bound)
  2531. if (o) {
  2532. // 遮挡
  2533. return true
  2534. }
  2535. })
  2536. if (block) {
  2537. //若不存在,即都遮挡了,就算真的遮挡
  2538. box.blocked[dir] = block
  2539. } else {
  2540. box.blocked[dir] = false
  2541. return false //找到一个方向无遮挡则可返回
  2542. }
  2543. }
  2544. }
  2545. return true
  2546. //暂定,若某个方向已得到遮挡了,就不计算。但若没有,就再搜一遍(如果会重复搜之后再增加一个stamp啥的,比如记录下当前所有solidBoxes的name,如果改变了就重新搜下)
  2547. } else {
  2548. //若中心方向已经有同类型的box,很可能它就是自身(因为挂墙的预测位置很不准,所以需要这一步。越tiny的越能通过此来筛选)
  2549. let block = boxesSolid.find(boxSolid => {
  2550. if (boxSolid.boxType != box.boxType) return
  2551. ray.set(box.pano.position, box.centerDir)
  2552. let o = ray.ray.intersectsBox(boxSolid.bound)
  2553. if (o) {
  2554. // 遮挡
  2555. return true
  2556. }
  2557. })
  2558. if (block) {
  2559. box.blocked = block
  2560. return true
  2561. }
  2562. }
  2563. }
  2564. //调试 O540aEVF3b7 jQUQlER160 n4z0yd5tQaF WcLVXvmV9AU 8czlwsbSe5 NlUM8yGve9
  2565. function findRest(groups /* ,startIndex=2 */) {
  2566. //查找是否有遗漏。
  2567. //1 可能有距离较远的box不在头两个pano的附近导致被漏掉。(概率很小)
  2568. //2 被剩余的 (包括低分匹配中放弃的,这种需要的距离识别度高)
  2569. const tolerateWidth = { min: 0.1, max: 0.5 }
  2570. let boxes = [],
  2571. scores = new Map(),
  2572. bestDisSquared = 2
  2573. groups.forEach(g => {
  2574. boxes.push(...g)
  2575. })
  2576. boxes = boxes.filter(box => !used(box))
  2577. boxes.forEach(box => {
  2578. getBoxBase(box)
  2579. let p1 = new THREE.Vector2(box.pano.position.x, box.pano.position.z)
  2580. let p2 = new THREE.Vector2(box.btmPos.x, box.btmPos.z)
  2581. let dis = p1.distanceToSquared(p2)
  2582. let s1 = -Math.abs(dis - bestDisSquared) //将距离最佳的排前面,距离远的得到的位置不准确,也容易被遮
  2583. if (!box.pose) box.pose = getBoxPoseByPos(box, getBoxPos(box))
  2584. let s2 = getPoseScore([box.pose], box.boxType) + THREE.MathUtils.clamp(box.pose.projectWidth, box.pose.minProjectWidth, box.pose.maxProjectWidth) * 7 //projectWidth长的更安全
  2585. scores.set(box, { s1, s2, sum: s1 + s2 })
  2586. })
  2587. //console.log(boxes[0].boxType,scores)
  2588. boxes = boxes.sort((a, b) => {
  2589. return scores.get(b).sum - scores.get(a).sum
  2590. }) //FXcq5PI9QGv
  2591. //console.log(boxes)
  2592. boxes.forEach(box => {
  2593. if (box.sid == 'pano0-4') {
  2594. console.log(3)
  2595. }
  2596. if (!used(box) && !blocked(box)) {
  2597. //如果和现有的box的距离都很远,很可能是漏掉的
  2598. let near = boxesSolid.find(solidBox => {
  2599. if (solidBox.name == 'air-pano16-7&pano14-13') {
  2600. console.log(3)
  2601. }
  2602. if (solidBox.boxType != box.boxType && (solidBox.boxType == 'air-hanging' || box.boxType == 'air-hanging')) return //挂空调一般不会撞到地面上的
  2603. let p1 = getBoxPos(solidBox)
  2604. let p2 = getBoxPos(box)
  2605. let p1_ = new THREE.Vector2(p1.x, p1.z)
  2606. let p2_ = new THREE.Vector2(p2.x, p2.z)
  2607. let maxWidth = standards[box.boxType].widthNormal.max / 2
  2608. maxWidth = THREE.MathUtils.clamp(maxWidth, tolerateWidth.min, tolerateWidth.max) //因为场景精度存在较大误差,所以maxWidth不能过小,否则像灭火器摄像头都容易findRest多个
  2609. let dis = solidBox.bound.distanceToPoint(p2)
  2610. //let r0 = solidBox.boxType == 'air' ? 2 : solidBox.boxType == 'battery' ? 1.1 : 1 //空调最不容易扎堆放置,所以范围设置广一些
  2611. let r0 = standards[box.boxType].closeRatio
  2612. let r1 = math.linearClamp(box.pano.position.distanceTo(p2), 3, 8, 1, 2) //距离远的话识别、计算都会更不准确,给一定的容错. 远的尽量不findRest,即尽量>0
  2613. let ra = (solidBox.boxType == box.boxType ? 1 : 0.5) * r0 * r1 //数字越小限制越大
  2614. /* let a = maxWidth * maxWidth * ra - p1_.distanceToSquared(p2_)
  2615. let b = -dis * dis * 0.7
  2616. let c = a + b*/
  2617. let c = maxWidth * ra - dis * 1.3
  2618. if (c > 0) {
  2619. //太近 不创建
  2620. console.log(1)
  2621. }
  2622. return c > 0
  2623. })
  2624. if (!near) {
  2625. reMatchLowScores([{ box0: box, log: 'findRest' }], groups, { startIndex: 0 })
  2626. } else {
  2627. //console.log('find near', near.name, box.sid)
  2628. }
  2629. }
  2630. })
  2631. }
  2632. function used(box) {
  2633. //是否已经使用过
  2634. let has = e => {
  2635. return e.box0 == box || e.box1 == box
  2636. }
  2637. let traverse = e => {
  2638. return (
  2639. has(e) ||
  2640. (e.list && e.list.some(a => traverse(a))) ||
  2641. (e.mixedFrom && e.mixedFrom.some(a => traverse(a))) ||
  2642. (e.infos && e.infos.some(u => u.group.some(r => r.boxes.some(b => b == box))))
  2643. ) //row
  2644. }
  2645. return boxesSolid.some(e => traverse(e))
  2646. }
  2647. function reMatchLowScores(lowScores, groups, { startIndex = 2, fake } = {}) {
  2648. let matched = [],
  2649. tooLows = []
  2650. let minScore = boundConfirmed ? -2000 : -800
  2651. let isSameMatch = (match0, match1) => {
  2652. //是否对应同一个box实体(不一定准),通过两两box之间是否都match来判断
  2653. //如果是相同pano但不同的box肯定不是对应同一个box实体
  2654. let ifWrong = (box0, box1) => {
  2655. if (box0 == box1) return
  2656. if (box0.pano == box1.pano) return true
  2657. let match2 = getMatchScore(box0, box1, { isSingle: true, restMatch: true })
  2658. if (match2.score < minScore) return true
  2659. }
  2660. if (ifWrong(match0.box0, match1.box0) || ifWrong(match0.box1, match1.box1) || ifWrong(match0.box0, match1.box1) || ifWrong(match0.box1, match1.box0)) return
  2661. return true
  2662. }
  2663. if (lowScores.length) {
  2664. console.warn(lowScores[0].log || (lowScores[0].box1 ? '低分重新匹配' : '剩余匹配'), lowScores[0].box0.boxType, ...lowScores)
  2665. if (lowScores[0].box1) {
  2666. lowScores.sort((a, b) => {
  2667. //低分优先
  2668. return a.score - b.score
  2669. })
  2670. }
  2671. lowScores.forEach(info => {
  2672. //info中的box0和box1分别向后寻找其他的配对。选择分数高的配对。 但box0和box1可能是错误配对,会导致找到了替代的也可能遗漏。
  2673. /* if (info.name == 'pano0-3&pano2-3') {
  2674. console.log(1)
  2675. } */
  2676. let box01 = info.box0
  2677. let box02 = info.box1
  2678. let bigGroup = []
  2679. box02 && bigGroup.push(info)
  2680. let got
  2681. for (let cur = startIndex; cur < groups.length; cur++) {
  2682. let thirdGroup = groups[cur]
  2683. let scores0 = [],
  2684. scores1 = []
  2685. thirdGroup.forEach(box1 => {
  2686. //if (matched.includes(box1.sid)) return
  2687. if (used(box1)) return //会不会太严格?
  2688. if (box1.pano != box01.pano && box1 != box02) {
  2689. let r1 = getMatchScore(box01, box1, { isSingle: true, restMatch: true })
  2690. r1.score > minScore * 1.5 && scores0.push(r1)
  2691. }
  2692. if (box02 && box1.pano != box02.pano && box1 != box01) {
  2693. let r2 = getMatchScore(box02, box1, { isSingle: true, restMatch: true })
  2694. r2.score > minScore * 1.5 && scores1.push(r2)
  2695. }
  2696. })
  2697. scores0.sort((a, b) => {
  2698. return b.score - a.score
  2699. })
  2700. scores1.sort((a, b) => {
  2701. return b.score - a.score
  2702. })
  2703. scores0[0] && bigGroup.push(scores0[0])
  2704. scores1[0] && bigGroup.push(scores1[0])
  2705. }
  2706. bigGroup.sort((a, b) => {
  2707. return b.score - a.score
  2708. })
  2709. let goodList = bigGroup.slice(0, 10).map(e => {
  2710. if (!getBoxPos(e)) return e
  2711. preDealBox(e)
  2712. getBoxSize(e)
  2713. return e
  2714. })
  2715. let goodList2 = goodList
  2716. .sort((a, b) => {
  2717. return b.score - a.score
  2718. })
  2719. .slice(0, 3)
  2720. if (goodList2.length == 0) {
  2721. return fake || createSinglePano(box01, 0.6) //minScorePercent原因:剩余匹配时位置不太好的案例: AhMgXXjM15
  2722. }
  2723. if (goodList2[0].score > minScore * 0.65) {
  2724. goodList2 = goodList2.filter(e => e.score > minScore * 0.65)
  2725. } else {
  2726. /* goodList2 = [goodList2[0]] // 最高分已经过小
  2727. if (goodList2[0].score < -1500) { */
  2728. if (!box02) {
  2729. if (info.log == 'findRest' || getBoxPos(box01).distanceTo(box01.pano.position) < 2.5) {
  2730. //远距离不准,留到过后findRest
  2731. fake || createSinglePano(box01)
  2732. }
  2733. return
  2734. }
  2735. //console.warn('分数过低,是否有匹配错误?', goodList2[0])
  2736. return tooLows.push(goodList2[0])
  2737. //}
  2738. }
  2739. if (goodList2.length) {
  2740. //需要确认两两之间是配对的,也就是都对应同一个box
  2741. let subGroups = [],
  2742. boxes = []
  2743. for (let i = 0, len = goodList2.length; i < len; i++) {
  2744. //向后选择队友
  2745. let match0 = goodList2[i]
  2746. if (subGroups.some(e => e.includes(match0))) continue //被挑选了的没有选择权
  2747. let gr = [match0]
  2748. for (let j = i + 1; j < len; j++) {
  2749. let match1 = goodList2[j]
  2750. if (isSameMatch(match0, match1)) {
  2751. //可能不是同一个,所以需要检验
  2752. gr.push(match1)
  2753. }
  2754. }
  2755. //if(gr.length>1){
  2756. subGroups.push(gr)
  2757. //}
  2758. }
  2759. //console.log('lowScores subGroups', subGroups)
  2760. subGroups.forEach(pair => {
  2761. boxes.push(mixMatchBox(pair, lowScores[0].log, fake))
  2762. })
  2763. fake || combineBoxes(boxes) //很可能其实还是同一个,需要检验是否要融合
  2764. }
  2765. })
  2766. //改为之后 findRest, 因为两者都single的可能性低
  2767. /* let judge = box => {
  2768. if (!used(box)) {
  2769. matched.push(box)
  2770. createSinglePano(box)
  2771. }
  2772. }
  2773. tooLows.forEach(e => {
  2774. judge(e.box0)
  2775. judge(e.box1)
  2776. }) */
  2777. }
  2778. }
  2779. function mixMatchBox(list, log, fake) {
  2780. let center = new THREE.Vector3(),
  2781. size = new THREE.Vector3(),
  2782. name,
  2783. bound = new THREE.Box3()
  2784. list.forEach(e => {
  2785. let _bound = new THREE.Box3().setFromCenterAndSize(getBoxFinalPos(e), e.size)
  2786. bound.union(_bound)
  2787. })
  2788. //bound.getCenter(center) //这两种获得center的方法哪个准?
  2789. bound.getSize(size)
  2790. list.forEach(e => center.add(getBoxPos(e)))
  2791. center.multiplyScalar(1 / list.length)
  2792. let { xProp, yProp } = list.find(e => e.xProp) || {}
  2793. if (xProp && list.find(e => e.xProp && e.xProp != xProp)) {
  2794. //如果有不同的话
  2795. xProp = yProp = null
  2796. }
  2797. let prefix = log == 'findRest' ? 'rest:' : 'low:'
  2798. let object = {
  2799. name: prefix + list.map(e => e.name),
  2800. boxType: list[0].boxType,
  2801. center,
  2802. size,
  2803. list,
  2804. xProp,
  2805. yProp,
  2806. }
  2807. xProp || getBoxDirProp(object)
  2808. let o = restrictSize(size.x, size.y, size.z, object)
  2809. size.x = o.x
  2810. size.y = o.y
  2811. size.z = o.z
  2812. object.fake = fake
  2813. let box = new Box(object)
  2814. //console.log('mixMatchBox', box)
  2815. return box
  2816. }
  2817. function combineBoxes(boxes, typeCount) {
  2818. //调试 tY4ot33f8vT UWrshepp0G5的一高一低的电箱
  2819. //判断这些实体boxes是否需要合并 主要用于重复识别(重叠面积较大) 电池还可能是拼接
  2820. const group = []
  2821. if (boxes.length > 1) {
  2822. let boxType = boxes[0].boxType
  2823. let { min, max } = standards[boxType].widthNormal
  2824. for (let i = 0, len = boxes.length; i < len - 1; i++) {
  2825. let box0 = boxes[i]
  2826. if (box0.fake) continue
  2827. for (let j = i + 1; j < len; j++) {
  2828. let box1 = boxes[j]
  2829. if (box1.fake) continue
  2830. let bound = box0.bound.clone().union(box1.bound)
  2831. let size = bound.getSize(new THREE.Vector3())
  2832. let intersect = box0.bound.intersectsBox(box1.bound)
  2833. if (box0.boxType == 'electric') {
  2834. console.log(1)
  2835. }
  2836. let minX = min,
  2837. minZ = min,
  2838. maxX = max,
  2839. maxZ = max,
  2840. maxY = standards[boxType].height.max
  2841. if (box0.xProp && box1.xProp && box0.xProp == box1.xProp) {
  2842. maxX = standards[boxType][box0.xProp].max
  2843. maxZ = standards[boxType][box0.yProp].max
  2844. /* minX = standards[boxType][box0.xProp].min
  2845. minZ = standards[boxType][box0.yProp].min */
  2846. if (box0.boxType != box1.boxType) {
  2847. //air & airSmart
  2848. maxX = Math.max(maxX, standards[box1.boxType][box1.xProp].max)
  2849. maxZ = Math.max(maxZ, standards[box1.boxType][box1.yProp].max)
  2850. /* minX = Math.min(minX, standards[box1.boxType][box1.xProp].min)
  2851. minZ = Math.min(minZ, standards[box1.boxType][box1.yProp].min) */
  2852. }
  2853. }
  2854. maxX = Math.max(maxX, box0.size.x, box1.size.x) //必须大于各自的size,否则无法去除本身就oversize的box中包含的
  2855. maxZ = Math.max(maxZ, box0.size.z, box1.size.z)
  2856. maxY = Math.max(maxY, box0.size.y, box1.size.y)
  2857. let r = intersect ? 1.5 : 1.3 /* / standards[box1.boxType].closeRatio */ //如果是没有交集,限制更大些
  2858. //若需要更精确的结果,可以getMixBox算出重叠面积,重叠少,且各自都不太小,就不合并。但考虑到电池边界很模糊,合并了也无大碍。
  2859. if (box0.boxType == 'battery') {
  2860. r *= 1.3 //比较可能扎堆
  2861. }
  2862. let maxDiff = 0.4,
  2863. maxDiffX = maxDiff,
  2864. maxDiffZ = maxDiff,
  2865. rx = r,
  2866. rz = r
  2867. if (standards[box0.boxType].atWall == 1) {
  2868. //在墙面上不可能叠放,所以厚度限制可放宽
  2869. let s = 4
  2870. if (box0.yProp == 'width') {
  2871. maxDiffX *= s
  2872. rx *= s
  2873. } else if (box0.xProp == 'width') {
  2874. maxDiffZ *= s
  2875. rz *= s
  2876. }
  2877. }
  2878. //如果某个点位含有类似和这俩相近的box: A9rCPzp2UD9两个fire合并了。好难写,算了
  2879. /* if(box0.boxType){
  2880. this.datasMixed
  2881. rx = rz = 1.1
  2882. } */
  2883. if (size.x - maxX < maxDiffX && size.x < maxX * rx && size.z < maxZ * rz && size.z - maxZ < maxDiffZ && size.y < maxY * r && size.y - maxY < maxDiff) {
  2884. //总size不会太大
  2885. common.pushToGroupAuto([box0, box1], group)
  2886. }
  2887. }
  2888. }
  2889. if (group.length) {
  2890. //虽然如果三个以上可能会超出maxWidth。 不过3个的概率很低,且可以限制宽度
  2891. group.forEach(pair => {
  2892. let boxTypes = []
  2893. let bound = new THREE.Box3()
  2894. pair.forEach(e => {
  2895. bound.union(e.bound)
  2896. e.dispose()
  2897. if (typeCount > 1) {
  2898. //判断boxType: 寻找所使用的box总分最高的boxType
  2899. let a = boxTypes.find(a => a.boxType == e.boxType)
  2900. let score = 0
  2901. let add = box => {
  2902. box && (score += box.score)
  2903. }
  2904. e.traversePair(e => {
  2905. add(e.box0)
  2906. add(e.box1)
  2907. })
  2908. if (a) {
  2909. a.score += score
  2910. } else {
  2911. boxTypes.push({ score, boxType: e.boxType })
  2912. }
  2913. }
  2914. })
  2915. if (typeCount > 1) {
  2916. boxTypes.sort((a, b) => {
  2917. return b.score - a.score
  2918. })
  2919. boxType = boxTypes[0].boxType
  2920. }
  2921. let size = bound.getSize(new THREE.Vector3())
  2922. let center = bound.getCenter(new THREE.Vector3())
  2923. let { xProp, yProp } = pair.find(e => e.xProp) || {}
  2924. if (xProp && pair.find(e => e.xProp && e.xProp != xProp)) {
  2925. //如果有不同的话
  2926. xProp = yProp = null
  2927. }
  2928. let info = {
  2929. name: 'mix:' + pair.map(e => ' ' + e.name),
  2930. mixedFrom: pair,
  2931. boxType,
  2932. center,
  2933. size,
  2934. xProp,
  2935. yProp,
  2936. }
  2937. xProp || getBoxDirProp(info)
  2938. let o = restrictSize(size.x, size.y, size.z, info)
  2939. size.x = o.x
  2940. size.y = o.y
  2941. size.z = o.z
  2942. let box = new Box(info)
  2943. console.error('混合', boxType, pair, box)
  2944. })
  2945. }
  2946. }
  2947. }
  2948. function combines(types) {
  2949. //合并boxSolids . battery经常嵌套
  2950. if (!(types instanceof Array)) types = [types]
  2951. let boxes = boxesSolid.filter(e => types.includes(e.boxType))
  2952. combineBoxes(boxes, types.length)
  2953. }
  2954. let createSinglePano = (box, minScorePercent = 1) => {
  2955. //仅用一个pano中的data来创建。 悬挂于墙上的准确性依赖于墙的准确性。
  2956. if (box.score < MinBoxInitialScore) {
  2957. //如Xszq2fv03b的电池pano8-0其实是纸箱、 WZQoMbNmNTu的pano14-0分数0.649
  2958. return console.error('取消createSinglePano: 线框识别分数低,可能错误', box)
  2959. }
  2960. getBoxBase(box)
  2961. let center = getBoxPos(box)
  2962. if (safeBound.distanceToPoint(center) > 0.5) {
  2963. return console.log('取消createSinglePano:超出safebound', box) //可能是错误的线框,如H7pg1tO9oeJ pano8-1
  2964. }
  2965. let info = {
  2966. name: box.sid,
  2967. box0: box,
  2968. center,
  2969. topPos: box.topPos,
  2970. btmPos: box.btmPos,
  2971. }
  2972. preDealBox(info)
  2973. const minScore = -500 * minScorePercent //调试 3MnIWabM6ne Tmo1vLp9Q13
  2974. let a = getPoseScore(info.boxposes, box.boxType /* true */)
  2975. if (!standards[box.boxType].bottom && box.btmPos) {
  2976. a -= (box.btmPos.y - groundY) * 3000 //底部被遮住一部分
  2977. }
  2978. let failed = a < minScore
  2979. console.log('createSinglePano', failed ? '失败' : '成功', 'pose score:', a, box.sid, box)
  2980. if (failed) return
  2981. //addLabel(center, 'center', { a: 0.3 })
  2982. //info.topPos && addLabel(info.topPos, 'topPos', { a: 0.3 })
  2983. info.score = a
  2984. getBoxSize(info)
  2985. new Box(info)
  2986. }
  2987. //去除挨得很近的漫游点,因为两个接近的点match出的值误差很大
  2988. {
  2989. this.removedDatas = {}
  2990. let panoIds = Object.keys(this.datas)
  2991. let len = panoIds.length
  2992. for (let i = 0; i < len; i++) {
  2993. let pano0 = player.model.panos.index[panoIds[i]]
  2994. for (let j = i + 1; j < len; j++) {
  2995. let pano1 = player.model.panos.index[panoIds[j]]
  2996. if (pano0.position.distanceToSquared(pano1.position) < 0.01) {
  2997. //离的很近。保留shape多的那个data
  2998. let remove
  2999. if (this.datas[panoIds[i]].shapes.length > this.datas[panoIds[j]].shapes.length) {
  3000. remove = panoIds[j]
  3001. } else {
  3002. remove = panoIds[i]
  3003. }
  3004. console.log(`删除pano${remove}的data,因pano${panoIds[i]}和pano${panoIds[j]}很近`)
  3005. this.removedDatas[remove] = this.datas[remove]
  3006. delete this.datas[remove]
  3007. }
  3008. }
  3009. }
  3010. }
  3011. //this.expandModelBound()
  3012. // if (version == 'vision') this.datasMixed = common.CloneObject(this.datas, null, [player.model.panos.list[0].constructor])
  3013. if (version == 'vision')
  3014. this.datasMixed = common.CloneObject(this.datas, null, undefined, data => {
  3015. return data['category']
  3016. })
  3017. /* Search('cabinet')
  3018. Search('air')
  3019. Search('battery') */
  3020. for (let i in typeNames) {
  3021. Search(i)
  3022. }
  3023. console.log('----FindRest----')
  3024. waitFindRest.forEach(e => {
  3025. findRest(...e.args)
  3026. if (e.type != 'air' && e.type != 'airSmart' && e.type != 'cabinet') combines(e.type)
  3027. })
  3028. combines(['air', 'airSmart']) //这两种合在一起combine,因为太像了容易识别出多个 nZrBdvRaDuC
  3029. console.log('cost:', Date.now() - startTime, 'ms, boxSolid:', this.boxesSolid)
  3030. }
  3031. /* let getSid = (function(){
  3032. let sid = 0
  3033. return function(){
  3034. return sid++
  3035. }
  3036. })() */
  3037. let done = () => {
  3038. for (let panoId in this.datas) {
  3039. if(!this.datas[panoId])continue
  3040. this.datas[panoId].shapes = this.datas[panoId].shapes.map((shape, i) => {
  3041. return Object.assign(
  3042. {
  3043. sid: 'pano' + panoId + '-' + i,
  3044. category: shape.category, //提前 便于调试
  3045. pano: player.model.panos.index[panoId],
  3046. index: i,
  3047. },
  3048. shape
  3049. )
  3050. })
  3051. }
  3052. this.panoBound = new THREE.Box3()
  3053. player.model.chunks.forEach(e => {
  3054. modelBound.union(e.geometry.boundingBox) //注:不用model.boundingBox是 因为union了pano的position的
  3055. })
  3056. //针对部分模型错误,只有底面的,union一下pano.position
  3057. let minY = Infinity,
  3058. minYs = []
  3059. let panos = player.model.panos.list.filter(e => e.isAligned())
  3060. panos.forEach(e => {
  3061. let bound = new THREE.Box3().setFromCenterAndSize(e.position, new THREE.Vector3(0.1, 0.1, 0.1))
  3062. modelBound.union(bound)
  3063. this.panoBound.union(bound)
  3064. minY = Math.min(e.floorPosition.y, minY)
  3065. //avePanoFY += e.floorPosition.y
  3066. minYs.push(e.floorPosition.y)
  3067. })
  3068. groundY = modelBound.min.y
  3069. minYs.sort((a, b) => {
  3070. return a - b
  3071. })
  3072. console.log(minYs)
  3073. let midFloorY = minYs[Math.floor(minYs.length / 2)]
  3074. console.error('minY', minY, 'midFloorY', midFloorY, '原groundY', groundY)
  3075. this.minY = minY
  3076. //部分模型底部高度错误
  3077. /* if (minY > groundY) {
  3078. console.error('minY > groundY', minY, groundY)
  3079. groundY = modelBound.min.y = midFloorY //案例nZrBdvRaDuC
  3080. } else {
  3081. if (groundY - minY > 0.05) console.warn('minY', minY, 'groundY', groundY)
  3082. groundY = modelBound.min.y = midFloorY , document.title += ' new' //修改以后未必更好所以暂时不修改 变更好的:eGhyf5QdVHA
  3083. } */
  3084. groundY = modelBound.min.y = midFloorY //这个y可能不准。需要通过fire的btmPos.y来确定
  3085. safeBound = this.safeBound = modelBound
  3086. groundPlane.setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, groundY, 0))
  3087. this.ifAnalyze && beginCompute()
  3088. if (version == 'vision') this.load(player.currentPano.id)
  3089. }
  3090. async function load(panoId) {
  3091. let data = await http.post('/service/scene/sceneMarkShape/getInfo', { num: player.$app.config.num, imagePath: panoId + '.jpg' })
  3092. // console.error(data)
  3093. if (!data.data || !data.success) return (this.datas[panoId] = null)
  3094. this.datas[panoId] = data.data
  3095. if (Object.keys(this.datas).length == panosCount && !player.model.panos.list.some(e => e.isAligned() && !(panoId in this.datas))) {
  3096. done()
  3097. }
  3098. }
  3099. async function loadAll() {
  3100. let data = await http.post('/service/shapes/sceneMarkShape/getInfos', { num: player.$app.config.num })
  3101. console.error(data)
  3102. if (!data.data || !data.success) return
  3103. data.data.forEach(e => {
  3104. let panoId = e.imagePath.split('.jpg')[0]
  3105. this.datas[panoId] = e
  3106. })
  3107. done()
  3108. }
  3109. let panosCount = 0
  3110. if (!dataList) {
  3111. /* player.model.panos.list.forEach(e => {
  3112. if (!e.isAligned()) return
  3113. panosCount++
  3114. load.bind(this)(e.id)
  3115. }) */
  3116. loadAll.bind(this)() //测试环境
  3117. } else {
  3118. //when version == 'output'
  3119. dataList.forEach(e => {
  3120. let panoId = e.imagePath.split('.jpg')[0]
  3121. this.datas[panoId] = e
  3122. })
  3123. done()
  3124. }
  3125. }
  3126. expandModelBound() {
  3127. //有的模型太窄,容易将一排的柜体当做墙壁。所以可以根据box位置扩展bound. (如果因为点位太少,导致内部的电池远超模型范围,就不管了。R7xZsmm9FsG)
  3128. const maxDis0 = 1, //最终位置不会超过这个距离
  3129. maxDis1 = 3 //搜寻范围。不可扩展太宽,否则不准确的框会飘很远,甚至多画多个box,如R7xZsmm9FsG
  3130. let newBound = modelBound.clone()
  3131. let list = []
  3132. for (let panoId in this.datas) {
  3133. if(!this.datas[panoId])continue
  3134. this.datas[panoId].shapes.forEach(box => {
  3135. getBoxBase(box)
  3136. if (box.sid == 'pano2-10') {
  3137. console.log(4)
  3138. }
  3139. if (box.btmPosPredict) {
  3140. let far = box.pano.position.distanceToSquared(box.btmPosPredict)
  3141. if (far > 20) return //太远不准
  3142. let dis = modelBound.distanceToPoint(box.btmPosPredict)
  3143. if (dis > 0 && dis < maxDis1) {
  3144. //maxDis1用来防air-hanging和一些错误的框
  3145. list.push({ box, dis })
  3146. }
  3147. }
  3148. })
  3149. }
  3150. list.sort((a, b) => a.dis - b.dis)
  3151. //let mid = list[Math.floor(list.length/2)]
  3152. let mid = list.length // /2
  3153. for (let i = 0; i < mid; i++) {
  3154. let box = list[i].box
  3155. let pos = box.btmPosPredict
  3156. if (list[i].dis > maxDis0) {
  3157. let p1 = pos.clone().clamp(modelBound.min, modelBound.max)
  3158. let vec = new THREE.Vector3().subVectors(pos, p1).normalize().multiplyScalar(maxDis0)
  3159. pos = new THREE.Vector3().addVectors(p1, vec)
  3160. }
  3161. let marginBound = new THREE.Box3().setFromCenterAndSize(pos, new THREE.Vector3(0.2, 0, 0.2))
  3162. newBound.union(marginBound)
  3163. }
  3164. skyBoxTight = new BoundingMesh(
  3165. newBound,
  3166. new THREE.MeshBasicMaterial({
  3167. side: THREE.DoubleSide,
  3168. wireframe: true,
  3169. transparent: true,
  3170. opacity: 0.05,
  3171. }),
  3172. 0
  3173. )
  3174. //skyBoxTight.visible = false
  3175. skyBoxTight.updateMatrixWorld() //不update的话raycaster是错的
  3176. meshGroup.add(skyBoxTight)
  3177. this.skyBoxTight = skyBoxTight
  3178. this.safeBound = this.safeBoundFirstVer = safeBound = newBound
  3179. boundConfirmed = true
  3180. console.log('bound1:', this.safeBound.min.toArray(), this.safeBound.max.toArray())
  3181. }
  3182. expandModelBound2(type) {
  3183. let material = skyBoxTight.material
  3184. skyBoxTight.geometry.dispose()
  3185. boxesSolid.forEach(e => {
  3186. if (e.boxType != type) return
  3187. this.safeBound.union(e.bound)
  3188. })
  3189. skyBoxTight = new BoundingMesh(this.safeBound, material, 0)
  3190. //skyBoxTight.visible = false
  3191. skyBoxTight.updateMatrixWorld() //不update的话raycaster是错的
  3192. meshGroup.add(skyBoxTight)
  3193. this.skyBoxTight = skyBoxTight
  3194. console.log('bound2:', this.safeBound.min.toArray(), this.safeBound.max.toArray())
  3195. }
  3196. /* adjustModelBound(type){
  3197. if(standards[type].atWall != 1)return //必须是挂墙的
  3198. this.lastSafeBound = this.safeBound.clone()
  3199. let list = []
  3200. let add = e => {
  3201. if (e.btmPos && e.box1 && e.minAng>10 ) {
  3202. //有 box1才能确定是getIntersect得到的pos
  3203. list.includes(e) || e.push(e)
  3204. }
  3205. }
  3206. this.boxesSolid.forEach((solidBox)=>{
  3207. if(solidBox.boxType != type)return
  3208. solidBox.traversePair(add)
  3209. })
  3210. let wallSides = {'x+': 0, 'x-': 0, 'z+': 0, 'z-': 0}
  3211. let getBoxSide = (e)=>{
  3212. for(let i in e.panosDir){
  3213. if(e.panosDir[i] != 0){
  3214. wallSides[i] += 1
  3215. }
  3216. }
  3217. }
  3218. if(list.length){
  3219. this.safeBound = this.panoBound.clone()
  3220. list.forEach((e)=>{
  3221. this.safeBound.union(e.bound)//还是说使用cIntersect来expand?
  3222. getBoxSide()
  3223. })
  3224. }
  3225. skyBoxTight = new BoundingMesh(this.safeBound, material, 0)
  3226. //skyBoxTight.visible = false
  3227. skyBoxTight.updateMatrixWorld() //不update的话raycaster是错的
  3228. meshGroup.add(skyBoxTight)
  3229. this.skyBoxTight = skyBoxTight
  3230. //主要目的,针对那些模型比room大得多的情况,比如多了门外的部分,造成墙面不准。
  3231. //monitor的可以完全决定位置。其他的只能收缩(但是不能收缩超过panos和第一次expand的那些btm的bound里)
  3232. //太麻烦了,且考虑到即使墙面完全准确也可能反倒把它变的不准的风险。
  3233. } */
  3234. /* 最低点使用fire的吗
  3235. MW6MEeCOy9Y 只有最近三个点和fire接近
  3236. 3MnIWabM6ne fire combine了
  3237. ov5NTEImzhW fire多个
  3238. n4z0yd5tQaF fire多两个错位离谱的。。 位置和显示的不一样。。
  3239. 5BaiXkK6Ag1 fire算的不太准 低了0.1 样本数仅两个
  3240. */
  3241. confirmGroundY(type) {
  3242. //利用fire来确定地面高度(会稍低于地板,但box框不打滑且xz更准,估计因box框比box大)。调试:3MnIWabM6ne up9PPZkx1px 4GqaqNdyjGfs GFbQi1LiSij
  3243. if (boundConfirmed) return
  3244. let btmYs = [],
  3245. pairs = [],
  3246. needCount = 5,
  3247. maxDis = 3,
  3248. btmY = 0
  3249. let add = e => {
  3250. if (e.btmPos && e.box1 /* && e.score >= minScore */) {
  3251. //有 box1才能确定是getIntersect得到的pos
  3252. pairs.push(e)
  3253. }
  3254. }
  3255. boxesSolid.forEach(e => {
  3256. if (e.boxType != type) return
  3257. e.traversePair(add)
  3258. })
  3259. let usePairs = pairs
  3260. if (pairs.length > needCount) {
  3261. //调试:Y8czF2Z3h9m
  3262. let disMap = new Map()
  3263. pairs.forEach(e => {
  3264. disMap.set(e, Math.max(e.box0.pano.position.distanceTo(e.box0.btmPosPredict), e.box1.pano.position.distanceTo(e.box1.btmPosPredict)))
  3265. })
  3266. pairs.sort((a, b) => {
  3267. return disMap.get(a) - disMap.get(b)
  3268. }) //距离从近到远 . 远处的高度可能偏离严重,就不管了,而且框也不一定准
  3269. usePairs = pairs.slice(0, needCount)
  3270. for (let i = needCount; i < pairs.length; i++) {
  3271. if (disMap.get(pairs[i]) < maxDis) {
  3272. usePairs.push(pairs[i])
  3273. }
  3274. }
  3275. }
  3276. usePairs.forEach(e => {
  3277. //有 box1才能确定是getIntersect得到的pos
  3278. let btmY_ = e.btmPos.y
  3279. const width = e.size.x / 2
  3280. let h0 = width / Math.tan(Math.acos(-e.box0.centerBtmDir.y)) //|centerBtmDir.y| 即俯视角度的cos
  3281. let h1 = width / Math.tan(Math.acos(-e.box1.centerBtmDir.y))
  3282. let h = Math.min(h0, h1) //选个小的吧,因浅的会更快接触到中心,虽然交点是两条射线最近点 不一定在fire中心
  3283. //如果毫无误差,且centerBtmDir.y相同,只要两条线centerBtmDir的xz相同,交点就是和地面的交点,而只要不同,交点就是和地面的交点,而只要不同,交点必然是在fire中心之下。随着minAng和centerBtmDir.y 交点在这中间变化
  3284. let r = math.linearClamp(e.minAng, 0, 90, 0, 1)
  3285. btmY_ += h * r
  3286. btmYs.push(btmY_)
  3287. btmY += btmY_
  3288. })
  3289. btmY /= btmYs.length
  3290. if (btmYs.length) {
  3291. console.error(
  3292. 'confirmGroundY',
  3293. btmY,
  3294. /* '样本数', btmYs.length, */ btmYs,
  3295. usePairs.map(e => e.name),
  3296. pairs
  3297. )
  3298. /* if(btmYs.length == 1 && pairs[0].minAngle<12 && ){
  3299. } */
  3300. groundY = this.safeBound.min.y = this.panoBound.min.y = btmY // = -1.1
  3301. groundPlane.setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, groundY, 0))
  3302. }
  3303. let { min, max } = standards[type].height
  3304. boxesSolid.slice().forEach(e => {
  3305. if (e.boxType != type) return
  3306. if (e.fake) {
  3307. e.dispose()
  3308. return
  3309. }
  3310. let topY = e.topPos
  3311. ? e.topPos.y
  3312. : e.list.reduce((w, c) => {
  3313. return w + c.topPos.y
  3314. }, 0) / e.list.length
  3315. e.size.y = THREE.MathUtils.clamp(topY - groundY, min, max)
  3316. e.setFromInfo(e)
  3317. if (version == 'vision') e.draw()
  3318. })
  3319. this.panoBound
  3320. this.expandModelBound()
  3321. }
  3322. bindEvents() {
  3323. if (version != 'vision') return
  3324. player.on(PlayerEvents.FlyingStarted, e => {
  3325. //if(e.mode == 'dollhouse')return
  3326. // 点位跳转前清除已有线框
  3327. this.traverse(obj => {
  3328. if (obj.isMesh) {
  3329. obj.geometry.dispose()
  3330. obj.material.dispose()
  3331. }
  3332. })
  3333. this.wireframes.clear()
  3334. this.currentId = null
  3335. })
  3336. player.on(PlayerEvents.FlyingEnded, () => {
  3337. // 点位跳转后加载线框
  3338. if (player.mode != Viewmode.PANORAMA) return // 只有PANORAMA模式下需要加载
  3339. this.load(player.currentPano.id)
  3340. })
  3341. window.boxFrame = this
  3342. if (this.ifAnalyze) {
  3343. setTimeout(() => {
  3344. {
  3345. let btn = document.createElement('button')
  3346. btn.innerHTML = '点击切换box显示'
  3347. btn.onclick = () => {
  3348. this.boxesSolid.forEach(e => ((e.boxHelper.visible = !e.boxHelper.visible), (e.label.visible = !e.label.visible)))
  3349. }
  3350. document.querySelector('#app').appendChild(btn)
  3351. btn.id = 'boxWire'
  3352. btn.style.position = 'fixed'
  3353. btn.style['z-index'] = '100'
  3354. btn.style.background = '#e00472'
  3355. btn.style.padding = '10px'
  3356. btn.style.bottom = '80px'
  3357. }
  3358. {
  3359. let btn = document.createElement('button')
  3360. btn.innerHTML = '点击切换矩形框显示'
  3361. btn.onclick = () => {
  3362. this.wireframes.visible = !this.wireframes.visible
  3363. }
  3364. document.querySelector('#app').appendChild(btn)
  3365. btn.id = 'wireframes'
  3366. btn.style.position = 'fixed'
  3367. btn.style['z-index'] = '100'
  3368. btn.style.background = '#419aff'
  3369. btn.style.padding = '10px'
  3370. btn.style.bottom = '130px'
  3371. }
  3372. }, 1000)
  3373. }
  3374. }
  3375. /**
  3376. * 加载点位标记数据
  3377. * @param {*} panoId
  3378. */
  3379. load(panoId) {
  3380. let data = this.datasMixed[panoId] || this.datas[panoId]
  3381. if (!data) {
  3382. if (!(panoId in this.datas))
  3383. setTimeout(() => {
  3384. this.load(panoId)
  3385. }, 100) //否则无数据
  3386. return
  3387. }
  3388. if (player.currentPano.id != panoId || player.flying || this.currentId == panoId) return // 防止连续跳转点位时,clear后才load好上一点位的数据,导致出现之前的标记
  3389. this.currentId = panoId
  3390. let { shapes, imageHeight, imageWidth } = data //data.data
  3391. let allShapes = shapes.slice()
  3392. shapes.forEach(e => {
  3393. if (e.boxes) allShapes.push(...e.boxes)
  3394. })
  3395. let fireIndex = 0
  3396. allShapes.forEach(shape => {
  3397. // 填充色和线框色
  3398. // let { fill_color, line_color } = shape
  3399. getUVs(shape)
  3400. getCenterDir(shape, player.currentPano)
  3401. let { fill_color, color = [56, 56, 255] } = shape
  3402. let line_color = [...color, 255]
  3403. if (!fill_color) fill_color = [255, 255, 255, 0]
  3404. if (!line_color) line_color = [255, 0, 0, 255]
  3405. if (shape.boxes) {
  3406. line_color = [20, 205, 255, 255]
  3407. }
  3408. let pos = getBoxPos(shape)
  3409. let dis = pos ? shape.pano.position.distanceTo(getBoxPos(shape)) : 1
  3410. let labelShift = (shape.boxType == 'fire' ? 0 : -0.2) / dis
  3411. this.showSignalFrom2d(
  3412. shape.category + '-' + shape.sid,
  3413. shape.bbox2,
  3414. imageWidth,
  3415. imageHeight,
  3416. {
  3417. fill: {
  3418. color: new THREE.Color().setRGB(fill_color[0] / 255, fill_color[1] / 255, fill_color[2] / 255),
  3419. opacity: fill_color[3] / 255,
  3420. },
  3421. line: {
  3422. color: new THREE.Color().setRGB(line_color[0] / 255, line_color[1] / 255, line_color[2] / 255),
  3423. opacity: shape.category == 'cabling_rack' ? 0.4 : line_color[3] / 255, //走线架太绕,扰乱视线
  3424. },
  3425. },
  3426. shape.centerDir,
  3427. labelShift,
  3428. shape.state == '被删除'
  3429. )
  3430. })
  3431. // })
  3432. // .catch(err => console.log(`点位${panoId}无标记数据或数据出错:`, err))
  3433. }
  3434. /**
  3435. * 根据坐标标记全景图
  3436. *
  3437. * 存在的问题:如果要准确复现全景图上的线框,上下边框会变为弧形。而按顶点连直线的话,180度以上会出bug。
  3438. * 解决方式:目前150度以下只画出4个顶点然后连直线,150度以上准确画出全景图线框。
  3439. */
  3440. showSignalFrom2d(name, rect, w, h, options, centerDir, labelShift, removed) {
  3441. // 目前rect给的是矩形对角的两个点坐标,将它扩展成四个顶点
  3442. let cornerArr = [new THREE.Vector2(rect[0], rect[1]), new THREE.Vector2(rect[2], rect[1]), new THREE.Vector2(rect[2], rect[3]), new THREE.Vector2(rect[0], rect[3])]
  3443. // 根据四个顶点,填充中间点
  3444. let pointArr = []
  3445. for (let i = 0; i < cornerArr.length; i++) {
  3446. let corner1 = cornerArr[i]
  3447. let corner2 = cornerArr[(i + 1) % cornerArr.length]
  3448. pointArr.push(corner1)
  3449. /* // 横向角度超过150度时,3d中边框的弧线已经不太明显,准确画出全景图线框
  3450. if ((rect[2] - rect[0]) / w < 5 / 12 && i % 2 == 0) continue
  3451. const vec = [corner2[0] - corner1[0], corner2[1] - corner1[1]]
  3452. let length = Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
  3453. let num = length / 150
  3454. for (let j = 1; j <= num; j++) {
  3455. pointArr.push([corner1[0] + (vec[0] / num) * j, corner1[1] + (vec[1] / num) * j])
  3456. } */
  3457. }
  3458. //pointArr.push(cornerArr[0], cornerArr[2], cornerArr[1], cornerArr[3]) //对角线
  3459. let points = []
  3460. pointArr.forEach(uv => {
  3461. let dir = getDirByUV(uv, player.currentPano)
  3462. // points.push(dir.sub(centerVec)) // 计算其他点相对于中点的坐标,方便旋转平移等
  3463. points.push(dir)
  3464. })
  3465. // 线框
  3466. const lineGeometry = new THREE.BufferGeometry().setFromPoints(points)
  3467. const lineMaterial = new THREE.LineBasicMaterial({ color: options.line.color, opacity: options.line.opacity, transparent: true, depthTest: false })
  3468. const wireframe = new THREE.LineLoop(lineGeometry, lineMaterial)
  3469. // wireframe.position.copy(centerVec) // 将中点作为线框坐标
  3470. wireframe.renderOrder = 100
  3471. // 填充颜色
  3472. const fillGeometry = lineGeometry.clone().setIndex(new THREE.BufferAttribute(new Uint16Array([0, 1, 3, 2, 3, 1]), 1))
  3473. const fillMaterial = new THREE.MeshBasicMaterial({ color: options.fill.color, opacity: options.fill.opacity, transparent: true, side: THREE.DoubleSide, depthTest: false })
  3474. const plane = new THREE.Mesh(fillGeometry, fillMaterial)
  3475. plane.renderOrder = wireframe.renderOrder - 1
  3476. wireframe.add(plane)
  3477. // 名称
  3478. const textMesh = new TextSprite({
  3479. text: name,
  3480. backgroundColor: { r: options.line.color.r * 255, g: options.line.color.g * 255, b: options.line.color.b * 255, a: options.line.opacity * 0.5 },
  3481. textColor: { r: 255, g: 255, b: 255, a: options.line.opacity * 1.1 },
  3482. borderRadius: 15,
  3483. renderOrder: wireframe.renderOrder + 1,
  3484. player: player,
  3485. })
  3486. //const shift = new THREE.Vector3(0, labelShift , 0)
  3487. textMesh.position.copy(centerDir /* .clone().add(shift).normalize() */)
  3488. textMesh.lookAt(0, 0, 0) // 看向相机
  3489. textMesh.scale.set(0.12, 0.12, 0.12)
  3490. /* let line = addLine(centerDir, shift, null, options.line.color)
  3491. line.material.opacity = options.line.opacity */
  3492. let group = new THREE.Group()
  3493. group.position.copy(player.currentPano.position)
  3494. group.add(wireframe)
  3495. group.add(textMesh)
  3496. //group.add(line)
  3497. this.wireframes.add(group)
  3498. if (removed) {
  3499. textMesh.sprite.material.opacity = 0.4
  3500. lineMaterial.opacity *= 0.6
  3501. lineMaterial.color.set('#efe')
  3502. }
  3503. }
  3504. }