PanoBoxFrame.js 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219
  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. //----------------------复制以下内容---------------------------------
  8. let player,
  9. skyBoxTight,
  10. meshGroup,
  11. modelBound = new THREE.Box3(),
  12. ray = new THREE.Raycaster(),
  13. groundPlane = new THREE.Plane()
  14. let groundY, safeBound, boundConfirmed //安全区域应该在扣除每种类型柜子大概的长宽的一半
  15. let hue = 0
  16. const MinBoxInitialScore = 0.65 //找不到匹配时,若box分数低于该值,不createSinglePano
  17. let boxesSolid = []
  18. let standards = {
  19. cabinet: {
  20. widthNormal: { min: 0.6, max: 0.7 }, //widthNormal是不计宽还是厚度的平均宽度
  21. height: { min: 0.7, max: 2.5, standard: 2 },
  22. },
  23. air: {
  24. widthNormal: { min: 0.35, max: 0.7 },
  25. width: { min: 0.6, max: 0.75 },
  26. thick: { min: 0.3, max: 0.4 },
  27. height: { min: 1.4, max: 2, standard: 1.8 }, //standard是通常出现的最高高度
  28. },
  29. 'air-hanging': {
  30. widthNormal: { min: 0.3, max: 1 },
  31. width: { min: 0.8, max: 1.1 },
  32. thick: { min: 0.2, max: 0.3 },
  33. height: { min: 0.3, max: 0.5, standard: 0.4 },
  34. bottom: { min: 0.8, max: 2.0 }, // 不绝对,大部分
  35. },
  36. battery: {
  37. widthNormal: { min: 0.4, max: 1.2 },
  38. width: { min: 0.7, max: 1.4 },
  39. thick: { min: 0.35, max: 0.5 },
  40. height: { min: 0.3, max: 1.3, standard: 1.1 }, //maxHeight
  41. //有的电池很小。考虑是否追加battery-little 并且限制大电池的长宽高比例
  42. },
  43. rowBigBox: {
  44. widthNormal: { min: 0.5, max: Infinity },
  45. height: { min: 0.7, max: 2.4, standard: 2 },
  46. },
  47. }
  48. let addLabel = (pos, text, { bgcolor, a } = {}) => {
  49. if (version != 'vision') return
  50. bgcolor = bgcolor ? new THREE.Color(bgcolor) : { r: 1, g: 1, b: 1 }
  51. let textMesh = new TextSprite({
  52. text: text || 'aaaaaa',
  53. textColor: { r: 0, g: 0, b: 0, a: 1 },
  54. backgroundColor: { r: bgcolor.r * 255, g: bgcolor.g * 255, b: bgcolor.b * 250, a: a || 0.8 },
  55. margin: { x: 5, y: 5 },
  56. borderRadius: 0,
  57. player: player,
  58. })
  59. textMesh.position.copy(pos)
  60. textMesh.scale.set(0.3, 0.3, 0.3)
  61. meshGroup.add(textMesh)
  62. return textMesh
  63. }
  64. let addLine = (origin, dir) => {
  65. var line1 = LineDraw.createLine([origin, origin.clone().add(dir.clone().multiplyScalar(20))])
  66. meshGroup.add(line1)
  67. }
  68. let getBoxPos = info => {
  69. return (info.preDealRes && info.preDealRes.position) || info.center || (info.type == 'air-hanging' ? info.posAtWall : info.btmPos) || info.posAtWall
  70. }
  71. let updateBoxType = info => {
  72. let type = info.category || info.box0.category
  73. if (info.sid == 'pano4-0') {
  74. console.log(3)
  75. }
  76. if (type == 'air') {
  77. let btm = info.btmPos || info.btmPos //btmPosAtWall
  78. if (!btm) {
  79. btm = getBoxBtm(info)
  80. }
  81. if (!btm) return
  82. let center = info.posAtWall || (info.preDealRes && info.preDealRes.position) || info.center
  83. const s = standards['air-hanging']
  84. if (btm.y - groundY > s.bottom.min) {
  85. let h0 = btm.y - groundY
  86. let h1 = (modelBound.max.y - center.y) / (modelBound.max.y - modelBound.min.y)
  87. let h2 = center.y - btm.y
  88. let score = h0 * 2 - h1 * 3 - h2 * 3
  89. if (score > 0) {
  90. type = 'air-hanging'
  91. }
  92. //console.error( score, h0,h1,h2, info.sid||info.name)
  93. } //注意:如果air被遮住底部,露出的部分只有一点,还是有可能被识别成air-hanging。只能希望
  94. //console.error( type, info.sid||info.name)
  95. }
  96. if (info.box0) {
  97. info.boxType = /* info.box0.type = */ type
  98. //info.box1 && (info.box1.type = type) //因为box0和box1不一定匹配,所以不能直接赋值
  99. } else {
  100. info.type = type
  101. }
  102. }
  103. let getBoxDirProp = info => {
  104. let xProp, yProp
  105. if (info.boxType == 'battery' || info.boxType == 'air-hanging' || info.boxType == 'air' || info.category == 'battery' || info.category == 'air') {
  106. //根据比例判断
  107. /* let r1 = Math.abs((center.x - skyBoxTight.position.x) / (center.z - skyBoxTight.position.z))
  108. let r2 = player.model.size.x / player.model.size.z
  109. if(!math.closeTo(r1,r2, 0.05)){
  110. if (r1<r2) {
  111. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  112. } else {
  113. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  114. }
  115. matchInfo.xProp = xProp
  116. matchInfo.yProp = yProp
  117. } */
  118. //根据距离判断
  119. let center = getBoxPos(info)
  120. let bound = safeBound
  121. let minXDiff = Math.min(center.x - bound.min.x, bound.max.x - center.x)
  122. let minYDiff = Math.min(center.z - bound.min.z, bound.max.z - center.z)
  123. if (!math.closeTo(minXDiff, minYDiff, 0.2) && (minXDiff < 0.7 || minYDiff < 0.7)) {
  124. if (minXDiff < minYDiff) {
  125. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  126. } else {
  127. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  128. }
  129. } else {
  130. let xWidthPossible = 0,
  131. yWidthPossible = 0
  132. if (info.category) {
  133. info.pose || (info.pose = getBoxPoseByPos(info, info.btmPos))
  134. xWidthPossible = info.pose.xWidthPossible
  135. yWidthPossible = info.pose.yWidthPossible
  136. } else {
  137. info.boxposes.forEach(e => {
  138. xWidthPossible += e.xWidthPossible
  139. yWidthPossible += e.yWidthPossible
  140. })
  141. }
  142. if (xWidthPossible > yWidthPossible) {
  143. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  144. } else {
  145. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  146. }
  147. }
  148. xProp && ((info.xProp = xProp), (info.yProp = yProp))
  149. }
  150. }
  151. let preDealBox = matchInfo => {
  152. if (matchInfo.preDealRes || !matchInfo.center) return
  153. matchInfo.preDealRes = {}
  154. matchInfo.boxType || updateBoxType(matchInfo)
  155. let minWidth = standards[matchInfo.boxType].widthNormal.min
  156. let needGetPose
  157. if (safeBound.distanceToPoint(matchInfo.center) > 0.1) {
  158. /* matchInfo.str && matchInfo.str.includes('outsideBound') */
  159. //const shrink = minWidth * 0.85
  160. //addLabel(matchInfo.center, '原')
  161. let finalPos = matchInfo.center.clone().clamp(safeBound.min, safeBound.max)
  162. matchInfo.preDealRes.position = finalPos
  163. //addLabel(finalPos, 'finalPos')
  164. updateBoxType(matchInfo)
  165. needGetPose = true
  166. }
  167. let center = getBoxPos(matchInfo)
  168. if (needGetPose || !matchInfo.boxposes) {
  169. matchInfo.boxposes = []
  170. ;[matchInfo.box0, matchInfo.box1].forEach(box => {
  171. box && matchInfo.boxposes.push(getBoxPoseByPos(box, center))
  172. })
  173. }
  174. //-----------------
  175. /* if(matchInfo.name == "pano0-4&pano2-1"){
  176. console.log(4)
  177. } */
  178. getBoxDirProp(matchInfo)
  179. }
  180. let getPoseScore = (boxposes, isSingle) => {
  181. let score = 0
  182. const minDis = 2
  183. if (boxposes[0].box.sid == 'pano12-7' && boxposes[1].box.sid == 'pano8-2') {
  184. console.log(4)
  185. }
  186. boxposes.forEach(pose => {
  187. //pose.lowR = pose.dis < minDis ? Math.pow(THREE.MathUtils.smoothstep(pose.dis / minDis, 0, 1),2) : 1 //太近的话误差大
  188. pose.lowR = pose.dis < minDis ? Math.pow(pose.dis / minDis, 1.4) : 1 //太近的话误差大
  189. if (pose.projectWidth > pose.maxProjectWidth) {
  190. score += Math.pow((pose.projectWidth - pose.maxProjectWidth) * pose.lowR * 5, 2) //超过的话数字较大所以乘的数小一些
  191. } else if (/* isSingle && */ pose.projectWidth < pose.minProjectWidth) {
  192. score += Math.pow((pose.minProjectWidth - pose.projectWidth) * pose.lowR * 10, 2)
  193. }
  194. })
  195. score = Math.min(score, 500) //压低一点,因为得的宽度可能不准
  196. if (boxposes.length == 2) {
  197. //每一个方向对应有四个方向(每个象限一个)看到的projectWidth应该接近。
  198. //先把camTangent转化为第一个象限的
  199. let camTangent0 = new THREE.Vector2(Math.abs(boxposes[0].camTangent.x), Math.abs(boxposes[0].camTangent.y))
  200. let camTangent1 = new THREE.Vector2(Math.abs(boxposes[1].camTangent.x), Math.abs(boxposes[1].camTangent.y))
  201. let a = camTangent0.dot(camTangent1)
  202. if (a > 0.75) {
  203. //0.9: 25度之内. 0.8: 36.8度之内
  204. let diff = Math.abs(boxposes[0].projectWidth - boxposes[1].projectWidth)
  205. boxposes.score2 = a * diff * 4000 * boxposes[0].lowR * boxposes[1].lowR
  206. score += boxposes.score2
  207. //console.warn('在同一个方向看到的projectWidth应该接近。 ', diff)
  208. }
  209. boxposes.camTangentCos = a
  210. }
  211. score = Math.min(score, 1000)
  212. return -score
  213. }
  214. let getBoxSize = info => {
  215. if (info.size) return
  216. //console.warn('开始算 ' + info.name)
  217. let exStr = '',
  218. warnStr = ''
  219. let x, y //求对角线的向量 x>0,y>0
  220. //假设盒子的长宽为x,y (x>0,y>0),视线切线单位向量为(k,m),投影距离:x'k+y'm.
  221. //由于盒子的对角线有四个可选方向,(类似四个象限) 则需要能使投影距离最长的一个对角线向量。
  222. //如,当k<0,m>0时,要使xk+ym 最大,必有x<0,y>0. 故 x = -x', y = y', 故 投影距离:x'k+y'm = x(-k)+ym 。
  223. //故无论km的符号如何,只要变为正数,再去联立方程即可得xy。
  224. //注:但是因为无法获取准确的投影距离(角平分线左右两边的端点到角平分线的距离不相等,垂足也无法确定),所以所算的误差非常大。
  225. if (info.name == 'pano2-0') {
  226. console.log(6)
  227. }
  228. let center = getBoxPos(info)
  229. let oriX, oriY
  230. if (info.predictSize) {
  231. ;(x = oriX = info.predictSize.x), (y = oriY = info.predictSize.y)
  232. } else {
  233. if (info.box1) {
  234. let x1 = info.boxposes[0].camTangent.x,
  235. x2 = info.boxposes[1].camTangent.x,
  236. y1 = info.boxposes[0].camTangent.y,
  237. y2 = info.boxposes[1].camTangent.y,
  238. w1 = info.boxposes[0].projectWidth, //Math.max(minProjectWidth1, this.boxposes[0].projectWidth),
  239. w2 = info.boxposes[1].projectWidth //Math.max(minProjectWidth2, this.boxposes[1].projectWidth)
  240. //如果识别到柜门上,(柜体被遮住了),整体中心就会在柜门上,且厚度小于真实值。
  241. if (x1 == 0) {
  242. y = w1
  243. x = (w2 - y2 * y) / x2
  244. } else {
  245. //联立方程得:
  246. y = (w2 - (x2 / x1) * w1) / (y2 - (x2 / x1) * y1)
  247. x = (w1 - y1 * y) / x1
  248. }
  249. //console.log('xy', { x, y })
  250. ;(x < 0.3 || x > 1.4) && (exStr += ' x:' + math.toPrecision(x, 2))
  251. ;(y < 0.3 || y > 1.4) && (exStr += ' y:' + math.toPrecision(y, 2))
  252. if (y < 0 || x < 0) {
  253. //console.log('<0 ?????????')
  254. warnStr = x < 0 ? 'x<0!' : 'y<0!'
  255. }
  256. ;(oriX = x), (oriY = y)
  257. } else {
  258. //single pano data
  259. /* x = oriX = info.boxposes[0].maxX //姑且取最大值
  260. y = oriY = info.boxposes[0].maxY */
  261. if (info.xProp) {
  262. let widthValue = standards[info.boxType].width
  263. let thickValue = standards[info.boxType].thick
  264. if (info.xProp == 'width') {
  265. x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, widthValue.min, widthValue.max)
  266. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, thickValue.min, thickValue.max)
  267. } else {
  268. x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, thickValue.min, thickValue.max)
  269. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, widthValue.min, widthValue.max)
  270. }
  271. } else {
  272. //x = oriX = y = oriY = (min+max)/2
  273. let standard = standards[info.boxType].widthNormal
  274. x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, standard.min, standard.max)
  275. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, standard.min, standard.max)
  276. }
  277. }
  278. let o = restrictSize(x, y, info)
  279. ;(x = o.x), (y = o.y)
  280. //按正常来说,得到的x,y都应>0,但是由于箱子会被遮挡,导致投影宽度比真实的小,算出的也不准,可能是负数
  281. //所以手动将过小的宽度矫正
  282. }
  283. /* if(info.name == "pano2-6"){
  284. console.log(7)
  285. } */
  286. let height
  287. if (info.boxType == 'air-hanging') {
  288. //挂式空调最好把长宽固定。 不过极少出错
  289. //center.y -= 0.1 //很可能过高
  290. height = standards[info.boxType].height.standard
  291. getBoxBtm(info)
  292. let d = center.y - info.btmPos.y
  293. center.y -= THREE.MathUtils.clamp((d - height / 2) / 2, -0.1, 0.1) //如果中心点到底部的距离和height的一半不同,中心点移动差值的一半
  294. } else {
  295. if (!info.topPos) getBoxTop(info)
  296. let { min, max } = standards[info.boxType].height
  297. height = THREE.MathUtils.clamp(info.topPos.y - groundY, min, max)
  298. }
  299. info.size = new THREE.Vector3(x, height, y)
  300. info.sizeAdjust = Math.pow(Math.abs(x - oriX), 1.3) + Math.pow(Math.abs(y - oriY), 1.3) //计算得到的值和标准值之间的差距,可以反映该info的匹配分值
  301. if (info.sizeAdjust) info.score = (info.score || 0) - Math.min(info.sizeAdjust * 100, 400)
  302. ;(info.size.oriX = oriX), (info.size.oriY = oriY)
  303. ;(info.exStr = exStr), (info.warnStr = warnStr)
  304. }
  305. let restrictSize = (x, y, info) => {
  306. let s
  307. if (info.boxType == 'battery' || info.boxType == 'air-hanging' || info.boxType == 'air') {
  308. let { xProp, yProp } = info
  309. if (xProp != void 0) {
  310. var { min, max } = standards[info.boxType][xProp]
  311. x = THREE.MathUtils.clamp(x, min, max)
  312. var { min, max } = standards[info.boxType][yProp]
  313. y = THREE.MathUtils.clamp(y, min, max)
  314. s = true
  315. }
  316. }
  317. if (!s) {
  318. var { min, max } = standards[info.boxType].widthNormal
  319. x = THREE.MathUtils.clamp(x, min, max)
  320. y = THREE.MathUtils.clamp(y, min, max)
  321. /* if (info.boxposes) { //经常被遮挡
  322. x = Math.min(x, ...info.boxposes.map(e => e.maxX))
  323. y = Math.min(y, ...info.boxposes.map(e => e.maxY))
  324. } */
  325. }
  326. return { x, y }
  327. }
  328. let getMixBox = (box0, box1) => {
  329. //重叠部分
  330. let box = new THREE.Box2()
  331. box.min.set(Math.max(box0.min.x, box1.min.x), Math.max(box0.min.y, box1.min.y))
  332. box.max.set(Math.min(box0.max.x, box1.max.x), Math.min(box0.max.y, box1.max.y))
  333. return box
  334. }
  335. let getBoxFinalPos = info => {
  336. //创建solidbox时的position
  337. let position
  338. let center = getBoxPos(info)
  339. if (info.boxType == 'air-hanging') {
  340. position = center
  341. } else {
  342. position = center.clone().setY(groundY + info.size.y / 2) //使着地
  343. }
  344. return position
  345. }
  346. const axises = [
  347. new THREE.Vector3(-1, 1, -1),
  348. new THREE.Vector3(1, 1, -1),
  349. new THREE.Vector3(1, 1, 1),
  350. new THREE.Vector3(-1, 1, 1),
  351. new THREE.Vector3(-1, -1, -1),
  352. new THREE.Vector3(1, -1, -1),
  353. new THREE.Vector3(1, -1, 1),
  354. new THREE.Vector3(-1, -1, 1),
  355. ]
  356. class Box {
  357. //结果
  358. constructor(info) {
  359. //preDealBox(info)
  360. this.setFromInfo(info)
  361. if (version == 'vision') this.draw()
  362. boxesSolid.push(this)
  363. }
  364. setFromInfo(info) {
  365. for (let i in info) {
  366. this[i] = info[i]
  367. }
  368. /* let h = info.size.y
  369. let standardH = standards[info.boxType].height.standard
  370. if (h > standardH) {
  371. h = standardH + Math.log(1 + (h - standardH) / 2) //Math.log2: 以2为底的对数 ,Math.log:自然对数
  372. info.size.y = h
  373. } */
  374. this.name = this.boxType + '-' + this.name
  375. this.position = getBoxFinalPos(this)
  376. let bound = new THREE.Box3().setFromCenterAndSize(this.position, this.size)
  377. this.bound = bound
  378. }
  379. draw() {
  380. hue += 0.06
  381. var color = new THREE.Color().setHSL(hue, 1, 0.75)
  382. this.boxHelper = new THREE.Box3Helper(this.bound, color)
  383. this.boxHelper.material.depthTest = false
  384. this.boxHelper.material.transparent = true
  385. this.boxHelper.renderOrder = 30
  386. let { warnStr, exStr } = this
  387. warnStr && (exStr += `【${warnStr}】`)
  388. this.label = addLabel(this.position, exStr ? [this.name, exStr] : this.name, { bgcolor: color })
  389. meshGroup.add(this.boxHelper)
  390. }
  391. dispose() {
  392. let index = boxesSolid.indexOf(this)
  393. if (index > -1) {
  394. boxesSolid.splice(index, 1)
  395. if (version == 'vision') {
  396. this.label.sprite.material.opacity = 0.2
  397. this.boxHelper.material.opacity = 0.1
  398. }
  399. }
  400. }
  401. toJson() {
  402. let json = {
  403. points: axises.map(axis => new THREE.Vector3().addVectors(this.position, this.size.clone().multiply(axis).multiplyScalar(0.5)).toArray()),
  404. category: this.boxType,
  405. sid: this.name,
  406. }
  407. return json
  408. }
  409. }
  410. class cabinet extends Box {
  411. constructor() {
  412. super()
  413. }
  414. }
  415. // 2d坐标转3d坐标
  416. let getDirByUV = (uv, pano) => {
  417. // 计算方向向量
  418. let yaw = -uv.x * (Math.PI * 2)
  419. let pitch = Math.PI / 2 - uv.y * Math.PI
  420. let dir = new THREE.Vector3()
  421. dir.copy(Vectors.RIGHT).applyAxisAngle(Vectors.BACK, pitch).applyAxisAngle(Vectors.UP, yaw).applyQuaternion(pano.quaternion)
  422. return dir
  423. }
  424. let getCenterDir = box => {
  425. if (box.centerDir) return
  426. //假设不存在在box中间拍摄的情况,所以y不会横跨两边
  427. let bbox = box.bbox2
  428. let center = { x: getBbox2center(bbox[0], bbox[2]), y: (bbox[1] + bbox[3]) / 2 }
  429. box.bbox2CenterX = center.x
  430. let dir = getDirByUV(center, box.pano)
  431. box.centerDir = dir
  432. let centerTop = { x: center.x, y: bbox[1] }
  433. box.centerTopDir = getDirByUV(centerTop, box.pano)
  434. let centerBtm = { x: center.x, y: bbox[3] }
  435. box.centerBtmDir = getDirByUV(centerBtm, box.pano)
  436. }
  437. let getOtherPos = box => {
  438. if (!boundConfirmed) {
  439. ray.set(box.pano.position, box.centerBtmDir)
  440. box.btmPosPredict = ray.ray.intersectPlane(groundPlane, new THREE.Vector3()) //没有的话就在空中 (部分air-hanging也会有)
  441. if (box.btmPosPredict) {
  442. const depth = box.category == 'cabinet' ? 0.5 : 0.4
  443. let dir2d = new THREE.Vector2(box.centerBtmDir.x, box.centerBtmDir.z).normalize().multiplyScalar(depth)
  444. box.btmPosPredict.x += dir2d.x
  445. box.btmPosPredict.z += dir2d.y
  446. //addLabel(box.btmPosPredict,'b_'+box.category+"_"+box.sid, {bgcolor:'#6ff',a:0.1})
  447. //box.btmPosPredict.clamp(safeBound.min, safeBound.max)
  448. }
  449. return
  450. }
  451. if (!box.btmPos) {
  452. getBoxBtm(box)
  453. }
  454. if (!box.topPos) {
  455. getBoxTop(box)
  456. }
  457. if (!box.posAtWall && (box.category == 'battery' || box.category == 'air')) {
  458. const shrink = 0.4
  459. ray.set(box.pano.position, box.centerDir)
  460. let o = ray.intersectObjects([skyBoxTight])
  461. box.posAtWall = new THREE.Vector3().addVectors(box.pano.position, box.centerDir.clone().multiplyScalar(o[0].distance - shrink))
  462. //因墙壁不准确,所以还是尽量不用墙的位置
  463. /* if(box.btmPos){
  464. let wallRatio = 0.5;
  465. if(new THREE.Vector3().subVectors(box.btmPos, box.posAtWall).setY(0).length() > 1 )wallRatio = 0.2 //可能墙壁位置不准,靠后了
  466. box.predictCenter = new THREE.Vector3().addVectors(box.btmPos.clone().multiplyScalar(1-wallRatio), box.posAtWall.clone().multiplyScalar(wallRatio))
  467. //box.predictCenter = new THREE.Vector3().addVectors(box.posAtWall, box.btmPos).multiplyScalar(0.5) //也许能当中心点? 虽然y会低一些
  468. addLabel(box.predictCenter, box.sid+'-preC')
  469. } */
  470. }
  471. updateBoxType(box)
  472. }
  473. let getUVs = box => {
  474. if (box.bbox2) return
  475. let uvs = []
  476. box.bbox2 = box.bbox.map((e, i) => {
  477. return i % 2 == 0 ? e / 4096 /* + 0.25 */ : e / 2048
  478. })
  479. }
  480. let getBoxBase = box => {
  481. getUVs(box)
  482. getCenterDir(box)
  483. getOtherPos(box)
  484. }
  485. let getBbox2Diff = (x1, x2) => {
  486. //获取x1-x2,如果x1在x2右边则为正
  487. if (Math.abs(x1 - x2) < 0.5) return x1 - x2
  488. else {
  489. if (x1 > x2) x1 -= 1
  490. else x2 -= 1
  491. return x1 - x2
  492. }
  493. }
  494. let getBbox2center = (x1, x2) => {
  495. //找中间位置
  496. if (Math.abs(x1 - x2) > 0.5) {
  497. //永远找小于180度的那一边
  498. return (x1 + x2 + 1) / 2 //另外半边
  499. } else {
  500. return (x1 + x2) / 2
  501. }
  502. }
  503. let getBoxPoseByPos = (box, centerPos, addDis = 0) => {
  504. //当得知box的大概位置时,求box在这个角度上的宽度、朝向
  505. //在这个方向看的box的宽度
  506. let angle = getBbox2Diff(box.bbox2[2], box.bbox2[0]) * Math.PI //角度的一半
  507. let dis = new THREE.Vector3().subVectors(box.pano.position, centerPos).setY(0).length() + addDis
  508. let projectWidth = 2 * Math.tan(angle) * dis //投影宽度 (准确的投影宽度无法求得,只能近似)
  509. let camDir = /* new THREE.Vector2(centerPos.x-box.pano.position.x, centerPos.z-box.pano.position.z).normalize() */ box.centerDir.clone().setY(0).normalize()
  510. let camTangent = math.getNormal({
  511. points: [
  512. { x: 0, y: 0 },
  513. /* camDir */ { x: camDir.x, y: camDir.z },
  514. ],
  515. }) //视线切线方向
  516. camTangent.x = Math.abs(camTangent.x)
  517. camTangent.y = Math.abs(camTangent.y)
  518. if (box.sid == 'pano4-6') {
  519. console.log(7)
  520. }
  521. let maxWidth = standards[box.type].widthNormal.max
  522. let minWidth = standards[box.type].widthNormal.min
  523. let maxProjectWidth = (camTangent.x + camTangent.y) * maxWidth //该角度下该类型允许的最大投影距离
  524. let minProjectWidth = (camTangent.x + camTangent.y) * minWidth
  525. let maxX = projectWidth / camTangent.x //可得x的最大值(假设y为0)
  526. let maxY = projectWidth / camTangent.y //可得y的最大值(假设x为0)
  527. //判断方向
  528. let o = { box, projectWidth, camTangent, maxProjectWidth, minProjectWidth, dis, maxX, maxY }
  529. if (box.category == 'battery' || box.category == 'air') {
  530. o.xWidthPossible = -Math.abs(projectWidth - camTangent.x * maxWidth - camTangent.y * minWidth)
  531. o.yWidthPossible = -Math.abs(projectWidth - camTangent.x * minWidth - camTangent.y * maxWidth)
  532. //在接近45度时容易不准。另外如果被遮住一部分更……
  533. }
  534. return o
  535. }
  536. let getBoxTop = info => {
  537. if (info.box1) {
  538. let o2 = getIntersect2(info.box0.pano.position, info.box0.centerTopDir, info.box1.pano.position, info.box1.centerTopDir)
  539. info.topPos = o2.pos3d
  540. info.diffHeight = o2.mid2 ? o2.mid2.distanceTo(o2.mid1) : 1
  541. info.topPos.y = (info.box0.topPos.y + info.box1.topPos.y) / 2 //原先的不准
  542. } else {
  543. //取btm上方对应的位置 ( 因为和skybox的交点会因离墙远而偏上或偏下)
  544. let box = info.box0 || info
  545. let btm = box.btmPos
  546. if (!btm) {
  547. btm = getBoxBtm(info)
  548. }
  549. box.topPos = btm.clone() //xz同btm,要求y
  550. let xDelta = btm.x - box.pano.position.x
  551. let zDelta = btm.z - box.pano.position.z
  552. let yDelta
  553. //因为pano有旋转所以btm和top的xz其实是不一样的,所以会有误差。 故这里选择delta较大的
  554. if (Math.abs(xDelta) < Math.abs(zDelta)) {
  555. yDelta = (zDelta * box.centerTopDir.y) / box.centerTopDir.z
  556. /* console.log('use z', box)
  557. if(Math.abs(xDelta)<0.1)console.error('!!!!!!!!!!!!!!!!!!!!!!! xDelta',xDelta, box.sid ) */
  558. } else {
  559. yDelta = (xDelta * box.centerTopDir.y) / box.centerTopDir.x
  560. // console.log('use x', box)
  561. }
  562. box.topPos.y = yDelta + box.pano.position.y
  563. let minHeight = info.boxType ? standards[info.boxType].height.min : box.category == 'air' ? 0.5 : standards[box.category].height.min
  564. let diffH = Math.max(box.topPos.y - btm.y, minHeight)
  565. box.topPos.y = btm.y + diffH
  566. info.topPos = box.topPos
  567. /* if (box.sid == 'pano2-1') {
  568. addLabel(box.topPos,'t_'+box.sid,{bgcolor:'#ff4399'})
  569. addLine(box.pano.position,box.centerTopDir)
  570. } */
  571. }
  572. return info.topPos
  573. }
  574. let getBoxBtm = info => {
  575. if (info.box1) {
  576. let o2 = getIntersect2(info.box0.pano.position, info.box0.centerBtmDir, info.box1.pano.position, info.box1.centerBtmDir)
  577. info.btmPos = o2.pos3d
  578. //info.btmPos.y = (info.box0.btmPos.y + info.box1.btmPos.y)/2 //原先的不准
  579. } else {
  580. let box = info.box0 || info
  581. if (!box.btmPos) {
  582. ray.set(box.pano.position, box.centerBtmDir)
  583. let o = ray.intersectObjects([skyBoxTight]) //如果skybound有问题,位置就会错
  584. box.btmPosOri = o[0].point.clone()
  585. box.btmPos = o[0].point.clone()
  586. let depth //缩进 //let depth = Math.abs(o[0].face.normal.y) > 0.9 ? 0.4 : -0.4
  587. if (box.category == 'battery') {
  588. //注:air-hanging主要用的是posAtWall
  589. updateBoxType(box)
  590. let { min, max } = standards.battery.widthNormal
  591. min = min * 0.8
  592. max = max * 0.8
  593. if (!box.xProp) getBoxDirProp(box)
  594. if (box.xProp == 'width') {
  595. depth = math.linearClamp(Math.abs(box.centerBtmDir.x), 0, 1, min, max)
  596. } else {
  597. depth = math.linearClamp(Math.abs(box.centerBtmDir.z), 0, 1, min, max)
  598. }
  599. if (box.sid == 'pano0-3') {
  600. addLabel(box.btmPos, 'b_' + box.sid, { bgcolor: '#ff4399' })
  601. }
  602. box.btmPos = o[0].point.clone()
  603. } else {
  604. let minA = Math.min(Math.abs(box.centerBtmDir.x), Math.abs(box.centerBtmDir.z))
  605. depth = math.linearClamp(minA, 0, 0.707, 0.3, 0.7) //在45度时需要最长的距离。主要针对cabinet
  606. //addLabel(box.btmPos,'b_'+box.sid,{bgcolor:'#ff4399'})
  607. }
  608. if (Math.abs(o[0].face.normal.y) < 0.9) depth *= -1 //at wall
  609. let dir2d = new THREE.Vector2(box.centerBtmDir.x, box.centerBtmDir.z).normalize().multiplyScalar(depth)
  610. box.btmPos.x += dir2d.x
  611. box.btmPos.z += dir2d.y
  612. //addLabel(box.btmPos,'b_'+box.sid,{bgcolor:'#ff4399'})
  613. }
  614. info.btmPos = box.btmPos
  615. }
  616. return info.btmPos
  617. }
  618. let getIntersect = (pano0Pos, dir0, pano1Pos, dir1) => {
  619. let pos0 = new THREE.Vector3().addVectors(pano0Pos, dir0)
  620. let pos1 = new THREE.Vector3().addVectors(pano1Pos, dir1)
  621. /* var {pos3d, mid1, mid2, behind} = math.getLineIntersect({ A: pano0Pos.clone(), B: pano1Pos.clone(), p1: pos0, p2: pos1 })
  622. */ //三维线若接近平行,算出的交点可能很近,不是实际应该无交点才对
  623. var pos2d = math.isLineIntersect(
  624. [
  625. { x: pano0Pos.x, y: pano0Pos.z },
  626. { x: pos0.x, y: pos0.z },
  627. ],
  628. [
  629. { x: pano1Pos.x, y: pano1Pos.z },
  630. { x: pos1.x, y: pos1.z },
  631. ],
  632. true
  633. ) //优先考虑水平面方向的交点
  634. if (pos2d) {
  635. let y0 = ((pos2d.x - pano0Pos.x) * dir0.y) / dir0.x + pano0Pos.y
  636. let y1 = ((pos2d.x - pano1Pos.x) * dir1.y) / dir1.x + pano1Pos.y
  637. //console.log(y1-y0)
  638. let pos3d = new THREE.Vector3(pos2d.x, (y0 + y1) / 2, pos2d.y)
  639. return { pos3d, diffHeight: Math.abs(y0 - y1) } //diffHeight越小越好
  640. }
  641. }
  642. //究竟哪个比较准 - - 可能两个都判断?
  643. let getIntersect2 = (pano0Pos, dir0, pano1Pos, dir1) => {
  644. let pos0 = new THREE.Vector3().addVectors(pano0Pos, dir0)
  645. let pos1 = new THREE.Vector3().addVectors(pano1Pos, dir1)
  646. let o = math.getLineIntersect2({ A: pano0Pos.clone(), B: pano1Pos.clone(), p1: pos0, p2: pos1, dir0, dir1 }) //不用getLineIntersect,因为这个针对热点写的,当无交点时选用的点不是想要的
  647. if (!o.pos3d) {
  648. console.error('getIntersect2 no result? ?')
  649. }
  650. return o
  651. }
  652. let searchPair = (beginItem, group0_, group1_, parentPairs, resultPairs) => {
  653. let pair = [] //只能是来自group0的
  654. if (parentPairs) {
  655. //元结点裂变出多个,来装新的pair
  656. let i = resultPairs.indexOf(parentPairs)
  657. resultPairs.splice(i, 1)
  658. }
  659. for (let j = 0; j < group1_.length; j++) {
  660. pair = [beginItem, group1_[j]]
  661. let newPairs //用来存放该组pair
  662. if (parentPairs) {
  663. newPairs = parentPairs.slice(0) //复制
  664. newPairs.push(pair)
  665. } else {
  666. newPairs = [pair] //新的容器
  667. }
  668. resultPairs.push(newPairs)
  669. let newGroup0 = group0_.slice(0)
  670. let newGroup1 = group1_.slice(0)
  671. let index = newGroup0.indexOf(pair[0])
  672. newGroup0.splice(index, 1)
  673. index = newGroup1.indexOf(pair[1])
  674. newGroup1.splice(index, 1)
  675. if (newGroup0.length > 0 && newGroup1.length > 0) {
  676. searchPair(newGroup0[0], newGroup0, newGroup1, newPairs, resultPairs)
  677. }
  678. }
  679. }
  680. let getLeftRight = boxArr => {
  681. //获取pano的boxes中最左和最右的bbox.x
  682. let lefts = boxArr.map(e => e.bbox2[0])
  683. let rights = boxArr.map(e => e.bbox2[2])
  684. lefts.sort((a, b) => getBbox2Diff(a, b))
  685. rights.sort((a, b) => getBbox2Diff(b, a))
  686. let leftX = lefts[0] //最左
  687. let rightX = rights[0] //最右
  688. return {
  689. leftX,
  690. rightX,
  691. }
  692. }
  693. export default class PanoBoxFrame extends THREE.Group {
  694. constructor(player_, ifAnalyze, dataList) {
  695. super()
  696. player = player_
  697. player.model.add(this)
  698. this.ifAnalyze = ifAnalyze
  699. this.wireframes = new THREE.Object3D()
  700. this.wireframes.name = 'wireframes'
  701. this.add(this.wireframes)
  702. this.matchScoreMap = {}
  703. this.bindEvents()
  704. meshGroup = new THREE.Object3D()
  705. meshGroup.name = 'testBox'
  706. this.add(meshGroup)
  707. this.compute(dataList)
  708. }
  709. async compute(dataList) {
  710. this.datas = {}
  711. this.datasMixed = {}
  712. this.boxesSolid = boxesSolid
  713. let compu = 0
  714. let beginCompute = () => {
  715. //获取匹配分数
  716. let getMatchScore = (box0, box1, { isSingle, center, onlyGet, dontCheckDis } = {}) => {
  717. let name0 = box0.sid + '&' + box1.sid
  718. let name1 = box1.sid + '&' + box0.sid
  719. let matchInfo0 = this.matchScoreMap[box1.category][name0]
  720. let matchInfo1 = this.matchScoreMap[box1.category][name1]
  721. let matchInfo = matchInfo0 || matchInfo1
  722. if (onlyGet) return matchInfo
  723. let name
  724. if (!matchInfo) {
  725. name = name0
  726. matchInfo = { name, box0, box1, center }
  727. this.matchScoreMap[box1.category][name] = matchInfo
  728. } else {
  729. return matchInfo
  730. }
  731. if (name == 'pano6-6&pano0-2') {
  732. console.log(5)
  733. }
  734. getBoxBase(box0)
  735. getBoxBase(box1)
  736. let A = box0.pano.position.clone()
  737. let B = box1.pano.position.clone()
  738. let AB = new THREE.Vector3().subVectors(B, A)
  739. let AB2d = new THREE.Vector2(AB.x, AB.z).normalize()
  740. 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()
  741. 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()
  742. let angleA = Math.acos(AB2d.dot(AP12d))
  743. let angleB = Math.PI - Math.acos(AB2d.dot(BP22d))
  744. let score = 100,
  745. str = []
  746. if (angleA + angleB > Math.PI + 0.2) {
  747. //无交点(比180大是因为中心角度有误差,所以给一定的容错)
  748. //console.log(`${panoId0}的第${box0.index}个与${panoId1}的第${box1.index}个因角度大于180度 不匹配`)
  749. return Object.assign(matchInfo, { score: -5000, str: ['angle>180'] })
  750. }
  751. if (box0.type != box1.type) {
  752. return Object.assign(matchInfo, { score: -5000, str: ['typeNotSame'] })
  753. }
  754. if (matchInfo.dirAngleXZ == void 0) {
  755. matchInfo.dirAngleXZ = THREE.MathUtils.radToDeg(Math.acos(AP12d.dot(BP22d))) //需要尽量接近90度算出来的交点会比较准
  756. //matchInfo.minAng = Math.min(180 - matchInfo.dirAngleXZ, matchInfo.dirAngleXZ)
  757. if (isSingle) {
  758. //单个匹配单个,而非多个匹配多个(没有固定到两个漫游点),所以可以直接寻找最优角度
  759. score += Math.sin(THREE.MathUtils.degToRad(matchInfo.dirAngleXZ)) * 300
  760. score += matchInfo.dirAngleXZ //另外角度越大越不容易偏向一边
  761. }
  762. }
  763. let shinkRatio = 1
  764. if (!dontCheckDis) {
  765. let r = box0.type == 'air' ? 1 : box0.type == 'cabinet' ? 0.9 : 0.7 //随着宽度增加而降低
  766. if (box0.type != 'air-hanging' && box0.btmPos && box1.btmPos) {
  767. //注:挂空调不应使用btmPosPredict
  768. let d = box0.btmPos.distanceToSquared(box1.btmPos)
  769. matchInfo.btmPosPreDis = d
  770. score -= d * 1500 * r * shinkRatio
  771. let a = box0.topPos.distanceToSquared(box1.topPos)
  772. matchInfo.topPosPreDis = a
  773. let u = a * 700 * r * shinkRatio
  774. let AP0 = new THREE.Vector2(box0.btmPos.x - A.x, box0.btmPos.z - A.z).lengthSq()
  775. let AP1 = new THREE.Vector2(box1.btmPos.x - B.x, box1.btmPos.z - B.z).lengthSq()
  776. if (AP0 < 0.4 || AP1 < 0.4) u *= 0.3 //太近
  777. score -= u
  778. } else if (box0.posAtWall && box1.posAtWall) {
  779. let d = box0.posAtWall.distanceToSquared(box1.posAtWall)
  780. matchInfo.wallPosPreDis = d
  781. score -= d * 500 * r //墙面不准所以分低
  782. }
  783. }
  784. if (!matchInfo.center) {
  785. let o = getIntersect2(A, box0.centerDir, B, box1.centerDir)
  786. matchInfo.center = o.pos3d.clone()
  787. let dir0 = new THREE.Vector3().subVectors(o.pos3d, A).normalize()
  788. let dir1 = new THREE.Vector3().subVectors(o.pos3d, B).normalize()
  789. let sum = dir0.dot(box0.centerDir) + dir1.dot(box1.centerDir)
  790. let wrongDir = sum < 1.9
  791. score -= (2 - sum) * 10000
  792. if (wrongDir) {
  793. str.push('wrongDir')
  794. return Object.assign(matchInfo, { score: score - 5000, str })
  795. }
  796. let minAng = Math.min(180 - matchInfo.dirAngleXZ, matchInfo.dirAngleXZ) //角度小的getIntersect2容易算不准
  797. if (!dontCheckDis && box0.type != 'air-hanging' && box0.btmPos && box1.btmPos) {
  798. let p0 = new THREE.Vector2(box0.btmPos.x, box0.btmPos.z)
  799. let p1 = new THREE.Vector2(box1.btmPos.x, box1.btmPos.z)
  800. let p = new THREE.Vector2(matchInfo.center.x, matchInfo.center.z)
  801. let dis = p0.distanceToSquared(p) + p1.distanceToSquared(p)
  802. let s = math.linearClamp(minAng, 0, 10, 0, 1)
  803. score -= dis * 1000 * s //如果距离较远就说明算的center误差大,不可信。可能有一个框不准确
  804. matchInfo.centerDrift = dis
  805. }
  806. getBoxBtm(matchInfo)
  807. //靠墙的有这些属性 可以帮助预测中心点
  808. let predict0 = (box0.type != 'air-hanging' && box0.btmPos) || matchInfo.topPos
  809. let predict1 = (box1.type != 'air-hanging' && box1.btmPos) || matchInfo.topPos
  810. let cr = math.linearClamp(minAng, 0, 10, 0.05, 0.4) //getIntersect2结果的权重
  811. if (predict0 && predict1) {
  812. matchInfo.center = new THREE.Vector3()
  813. .addVectors(
  814. matchInfo.center
  815. .clone()
  816. .add(matchInfo.btmPos)
  817. .multiplyScalar((1 / 2) * cr),
  818. predict0
  819. .clone()
  820. .add(predict1)
  821. .multiplyScalar((1 / 2) * (1 - cr))
  822. )
  823. .setY(o.pos3d.y)
  824. }
  825. //addLabel(matchInfo.center, matchInfo.name + '-c')
  826. }
  827. updateBoxType(matchInfo)
  828. if (matchInfo.boxType != box0.type || matchInfo.boxType != box1.type) {
  829. ;(score -= 1000), str.push('typeNotSame2')
  830. }
  831. {
  832. let vec0 = new THREE.Vector3().subVectors(box0.pano.position, matchInfo.center)
  833. let vec1 = new THREE.Vector3().subVectors(box1.pano.position, matchInfo.center)
  834. if (vec0.x * vec1.x > 0 && vec0.z * vec1.z > 0) {
  835. //同一个象限(偏向一侧)
  836. score -= 200
  837. }
  838. }
  839. if (!safeBound.containsPoint(matchInfo.center)) {
  840. let dis = safeBound.distanceToPoint(matchInfo.center)
  841. //console.log(`${panoId0}的第${box0.index}个与${panoId1}的第${box1.index}个因中心点在bounding外不匹配`, center, 'dis: ' + dis)
  842. ;(score -= 1000 * dis * dis), str.push('outsideBound')
  843. Object.assign(matchInfo, { score, str, center: matchInfo.center, disToBound: dis })
  844. if (dis > 0.5) return matchInfo
  845. }
  846. //检查宽度
  847. let boxposes
  848. let checkWidth = () => {
  849. boxposes = []
  850. ;[box0, box1].forEach(box => {
  851. let pose = getBoxPoseByPos(box, matchInfo.center)
  852. boxposes.push(pose)
  853. //如果超出标准,基本上这二者不匹配;但过小的话,有可能是被遮挡所以残缺,因此不予过滤
  854. })
  855. }
  856. checkWidth()
  857. score += getPoseScore(boxposes, isSingle) //根据投影信息预测的长度再得匹配分数
  858. compu++
  859. return Object.assign(matchInfo, { score: score, str, /* diffHalfHeight, */ boxposes })
  860. /* preDealBox(matchInfo)
  861. getBoxSize(matchInfo) */
  862. }
  863. this.rows = {}
  864. /* let getchainNext = (left, end, chain, boxes) => {
  865. chain.push(left)
  866. if (left == end) return boxes.chains.push(chain)
  867. let nodes = boxes.relationships.filter(pair => pair.includes(left))
  868. let rights = nodes.map(pair => pair.find(e => e != left))
  869. rights = rights.filter(e => !chain.includes(e) && boxes.indexOf(e) > boxes.indexOf(left))
  870. rights.forEach(right => {
  871. getchainNext(right, end, chain.slice(), boxes)
  872. })
  873. } */
  874. let getPanoBigRowBox = (panoBoxes, { reason = 'row' } = {}) => {
  875. //将一个pano中的所有boxes分组,识别哪些是一排的。也可用于识别融合
  876. let pano = panoBoxes[0].pano
  877. const category = panoBoxes[0].category
  878. let type = category + '|' + reason
  879. this.rows[type] || (this.rows[type] = {})
  880. if (this.rows[type][pano.id]) return this.rows[type][pano.id]
  881. let bigBoxes
  882. let bigBox = {
  883. sid: 'pano' + pano.id + (reason == 'mix' ? '-mix' : '-row'),
  884. pano,
  885. category: 'rowBigBox',
  886. type: 'rowBigBox',
  887. }
  888. let rows = []
  889. for (let i = 0; i < panoBoxes.length; i++) {
  890. let box0 = panoBoxes[i]
  891. getBoxBase(box0)
  892. let [left0, right0] = [box0.bbox2[0], box0.bbox2[2]]
  893. for (let j = i + 1; j < panoBoxes.length; j++) {
  894. let box1 = panoBoxes[j]
  895. getBoxBase(box1)
  896. if (box0.type != box0.type) continue //类型不同
  897. let [left1, right1] = [box1.bbox2[0], box1.bbox2[2]]
  898. //let atEdge = (left1 < 0.00025 && right0 > 0.9997) || (left0 < 0.00025 && right1 > 0.9997) //在全景图的边界必会分两半
  899. let d1 = getBbox2Diff(left1, right0),
  900. d2 = getBbox2Diff(left1, left0),
  901. d3 = getBbox2Diff(left0, right1)
  902. /* if(box0.sid == "pano10-1"){
  903. console.log(9)
  904. } */
  905. const min = reason == 'mix' ? 0.004 : 0.003 //mix代表寻找分裂的重新融合到一起
  906. if ((d1 <= min && d2 >= min) || (d3 <= min && d2 <= min)) {
  907. //边框交接
  908. let atEdgeMight = left1 < 0.001 && right0 > 0.999 ? [left1, right0] : left0 < 0.001 && right1 > 0.999 ? [left0, right1] : null //有在全景图的边界的可能性
  909. if (reason == 'mix' && box0.category == 'cabinet' && !atEdgeMight) continue //柜子容易并排,尽量不融合
  910. /* if(box0.sid == 'pano2-1' && box1.sid == 'pano2-4'){
  911. console.log(3)
  912. } */
  913. const { min, max } = standards[box0.btmPos ? category : 'air-hanging'].widthNormal
  914. const w = (min + max) / 2
  915. const tolerate = w * w * (reason == 'mix' ? 0.8 : 2.1)
  916. let p0 = box0.type == 'air-hanging' ? box0.posAtWall : box0.btmPosOri
  917. let p1 = box1.type == 'air-hanging' ? box1.posAtWall : box1.btmPosOri
  918. let dis = p0.distanceToSquared(p1)
  919. if (reason == 'mix') {
  920. //disY = (Math.abs(box0.bbox2[3] - box1.bbox2[3]) + Math.abs(box0.bbox2[1] - box1.bbox2[1])) * 6 //边框纵向差异越大越不可能融合(虽然是可能有包含的情况啦,留到最后再combine。因为在侧面看,近处的box很容易嵌套远处的box,但它们不该融合)
  921. //dis += disY //SGyhEzZNGP9案例:虽然是atEdge但并不应该融合,便通过disY来阻挡
  922. let allY = (box0.bbox2[3] - box0.bbox2[1]) + (box1.bbox2[3] - box1.bbox2[1])//各自高度和
  923. let wholeY = Math.max(box0.bbox2[3],box1.bbox2[3]) - Math.min(box0.bbox2[1],box1.bbox2[1]) //总跨越高度
  924. let coverY = allY - wholeY //重合区域的y高度,可为负数
  925. let disY = ((1 - coverY / wholeY) + (wholeY - coverY)*3.5) * 4 * tolerate //既要考虑占比也要考虑差值
  926. dis += disY
  927. console.log('disY',disY, box0.sid, box1.sid )
  928. let atEdgePossib = atEdgeMight ? 0.002 / (atEdgeMight[0] + (1 - atEdgeMight[1])) : 0 // 两条线越接近越可能融合
  929. atEdgePossib = Math.min(6, atEdgePossib) //原本计算得 min:1, max:Infinity
  930. dis -= atEdgePossib * tolerate //给点点优势
  931. }
  932. /* if(box0.sid == "pano2-0"){
  933. console.log('dis',dis,'tolerate',tolerate,[box0, box1],disY)
  934. } */
  935. if(box0.sid == 'pano2-1' && box1.sid == 'pano2-4'){
  936. reason == 'mix' && console.log(dis, tolerate, box0.sid, box1.sid )
  937. }
  938. if (dis < tolerate) {
  939. reason == 'mix' && console.log('-------------------')
  940. common.pushToGroupAuto([box0, box1], rows)
  941. }
  942. }
  943. }
  944. }
  945. //一排箱子的角度范围不可超过180度,因为不可能站在箱子上拍,所以超过的话肯定有边缘的不在这一排中。
  946. //可判断边缘箱子的是否角度偏大,一般中间的被遮挡所以偏小
  947. rows.forEach(boxes => {
  948. //从左到右排序
  949. boxes.sort((a, b) => {
  950. //但因有的box跨越到别的box区域,所以这个顺序不准确
  951. return getBbox2Diff(a.bbox2CenterX, b.bbox2CenterX)
  952. })
  953. })
  954. //去除不在一条直线上的连接
  955. rows.slice(0).forEach(boxes => {
  956. if (boxes.length >= 2) {
  957. let removes = [],
  958. bound = new THREE.Box2(),
  959. size = new THREE.Vector2(),
  960. maxW = 0.6
  961. for (let i = 0, j = boxes.length; i < j; i++) {
  962. let box = boxes[i]
  963. let pos2d = new THREE.Vector2(box.btmPos.x, box.btmPos.z)
  964. bound.expandByPoint(pos2d)
  965. bound.getSize(size)
  966. let min = Math.min(size.x, size.y)
  967. if (min > maxW) {
  968. removes.push([boxes[i], boxes[i - 1]])
  969. bound = new THREE.Box2()
  970. bound.expandByPoint(pos2d)
  971. console.log('removes', size)
  972. }
  973. //console.log('removes',k, box1.sid)
  974. }
  975. if (removes.length) {
  976. console.log(
  977. '去除错误row连接',
  978. removes.map(e => e.map(a => a.sid))
  979. )
  980. let { newGroups } = common.disconnectGroup(removes, rows)
  981. //if(newGroups.length>1){//分裂成多组了,重新计算
  982. // console.log(newGroups)
  983. //}
  984. }
  985. }
  986. })
  987. rows.forEach(boxes => {
  988. //从左到右重新排序
  989. boxes.sort((a, b) => {
  990. //但因有的box跨越到别的box区域,所以这个顺序不准确
  991. return getBbox2Diff(a.bbox2CenterX, b.bbox2CenterX)
  992. })
  993. })
  994. /* rows.slice(0).forEach(boxes => {
  995. if (boxes.length >= 2) {
  996. let removes = [], minDiff = 1, minDis = 0.4
  997. let lastFirst = 0
  998. for (let i = 1, j = boxes.length; i < j-1; i++) {
  999. let box0 = boxes[lastFirst],
  1000. box1 = boxes[i] ,
  1001. box2 = boxes[i+1]
  1002. let vec0 = new THREE.Vector3().subVectors(box0.btmPos,box1.btmPos)
  1003. let vec1 = new THREE.Vector3().subVectors(box1.btmPos,box2.btmPos)
  1004. let angle = vec0.angleTo(vec1)
  1005. if(angle>minDiff){
  1006. removes.push([boxes[i], boxes[i + 1]])
  1007. lastFirst = i
  1008. console.log('removes', angle)
  1009. }
  1010. }
  1011. if (removes.length) {
  1012. console.log(
  1013. '去除错误row连接',
  1014. removes.map(e => e.map(a => a.sid))
  1015. )
  1016. let { newGroups } = common.disconnectGroup(removes, rows)
  1017. //if(newGroups.length>1){//分裂成多组了,重新计算
  1018. // console.log(newGroups)
  1019. //}
  1020. }
  1021. }
  1022. }) */
  1023. /* rows.slice(0).forEach(boxes => {
  1024. //有的其实是分离的但也在边缘连上了,可以根据底部的差来判断,过大的很可能是分离的
  1025. if (boxes.length >= 2) {
  1026. let diffs = []
  1027. for (let i = 0, j = boxes.length; i < j - 1; i++) {
  1028. let box0 = boxes[i],
  1029. box1 = boxes[i + 1]
  1030. let p0 = box0.predictCenter || box0.btmPos || box0.posAtWall
  1031. let p1 = box1.predictCenter || box1.btmPos || box1.posAtWall
  1032. diffs.push(p0.distanceToSquared(p1))
  1033. }
  1034. let minW = standards[category].widthNormal.min
  1035. if(!boxes[0].btmPos)minW = standards['air-hanging'].widthNormal.min
  1036. let mid = minW * minW
  1037. let removes = []
  1038. diffs.forEach((e, i) => {
  1039. if (e > mid * 2) {
  1040. removes.push([boxes[i], boxes[i + 1]])
  1041. }
  1042. })
  1043. if (removes.length) {
  1044. console.log(
  1045. '去除错误row连接',
  1046. removes.map(e => e.map(a => a.sid))
  1047. )
  1048. let { newGroups } = common.disconnectGroup(removes, rows)
  1049. //if(newGroups.length>1){//分裂成多组了,重新计算
  1050. // console.log(newGroups)
  1051. //}
  1052. }
  1053. }
  1054. }) */
  1055. rows.sort((a, b) => {
  1056. return b.length - a.length
  1057. }) //箱子数量从大到小排序
  1058. bigBoxes = rows.map((boxes, i) => {
  1059. let { leftX, rightX } = getLeftRight(boxes) //最左
  1060. let topY = boxes.slice().sort((a, b) => a.bbox2[1] - b.bbox2[1])[0].bbox2[1]
  1061. let btmY = boxes.slice().sort((a, b) => b.bbox2[3] - a.bbox2[3])[0].bbox2[3]
  1062. let rowBigBox = Object.assign({}, bigBox, {
  1063. boxes,
  1064. bbox2: [leftX, topY, rightX, btmY], //整排的bbox
  1065. left: boxes.find(e => e.bbox2[0] == leftX),
  1066. right: boxes.find(e => e.bbox2[2] == rightX),
  1067. })
  1068. let p0 = getBoxPos(rowBigBox.left)
  1069. let p1 = getBoxPos(rowBigBox.right)
  1070. let vec = new THREE.Vector2(p0.x - p1.x, p0.z - p1.z)
  1071. rowBigBox.k = Math.abs(vec.x / vec.y)
  1072. rowBigBox.predictLen = (rowBigBox.k > 1 ? Math.abs(vec.x) : Math.abs(vec.y)) + 0.6 //加入一个宽度
  1073. /* if(boxes.length <= boxes.relationships.length){//多条链
  1074. boxes.chains = []
  1075. getchainNext(left,right,[], boxes )
  1076. let aveAngle = (getBbox2Diff(left.bbox2[2], left.bbox2[0]) + getBbox2Diff(right.bbox2[2], right.bbox2[0]) ) / 2 -0.01 //首尾的angle平均数。但如果这两个不准那就导致整体出错了
  1077. let middleAngle = getBbox2Diff(right.bbox2[0], left.bbox2[2])
  1078. let counts = boxes.chains.map(e=>e.length)
  1079. counts.sort((a,b)=>a-b)
  1080. let min = counts[0],max = counts[counts.length-1]
  1081. let r = [], cur = min;
  1082. while(cur<=max){
  1083. r.push({cur, diff:Math.abs((middleAngle / (cur-2) - aveAngle)}) //加 0.01是因为增加边缘
  1084. cur++
  1085. }
  1086. r.sort((a,b)=>a.diff-b.diff)
  1087. rowBigBox.predictBoxCount = r[0].cur
  1088. //---------
  1089. let goodCountChains = boxes.chains.filter(e=>e.length == rowBigBox.predictBoxCount)
  1090. if(goodCountChains.length == 1) rowBigBox.bestChain = goodCountChains[0]
  1091. else{
  1092. goodCountChains = goodCountChains.map((chain,i)=>{
  1093. let j = 1, diff=0 //中间的box的angle的方差
  1094. while(j<rowBigBox.predictBoxCount){
  1095. let angle = getBbox2Diff(chain[j].bbox2[2], chain[j].bbox2[0])
  1096. diff += Math.pow(angle - aveAngle, 2)
  1097. j++;
  1098. }
  1099. return {diff, chain}
  1100. })
  1101. goodCountChains.sort((a,b)=>a.diff-b.diff)
  1102. rowBigBox.bestChain = goodCountChains[0].chain
  1103. }
  1104. console.log('getChains',boxes.chains, 'predictBoxCount',rowBigBox.predictBoxCount, r)
  1105. } */
  1106. return rowBigBox
  1107. })
  1108. if (reason != 'mix') {
  1109. panoBoxes.forEach(box => {
  1110. //加入单个的
  1111. if (!rows.some(row => row.includes(box))) {
  1112. let boxBig = Object.assign({}, bigBox, {
  1113. bbox2: box.bbox2,
  1114. boxes: [box],
  1115. left: box,
  1116. right: box,
  1117. })
  1118. bigBoxes.push(boxBig)
  1119. }
  1120. })
  1121. }
  1122. //mix的之前的btm因pose错误而延伸了不对的depth所以不准
  1123. bigBoxes.forEach(bigBox => {
  1124. bigBox.sid += '-' + bigBox.boxes.map(e => e.index).join(',')
  1125. /* if (bigBox.sid == 'pano0-rowBigBox-1,0,2,4') {
  1126. console.log(3)
  1127. } */
  1128. if (reason == 'row') {
  1129. //取平均值
  1130. if (bigBox.boxes[0].btmPos) {
  1131. bigBox.btmPos = bigBox.boxes.reduce((w, c) => w.add(c.btmPos), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1132. //addLabel(bigBox.btmPos,'b_'+bigBox.sid, {bgcolor:'#f93',a:0.4})
  1133. }
  1134. if (bigBox.boxes[0].topPos) {
  1135. bigBox.topPos = bigBox.boxes.reduce((w, c) => w.add(c.topPos), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1136. }
  1137. if (bigBox.boxes[0].posAtWall) {
  1138. bigBox.posAtWall = bigBox.boxes.reduce((w, c) => w.add(c.posAtWall), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1139. }
  1140. }
  1141. })
  1142. this.rows[type][pano.id] = bigBoxes //当前pano的所有row
  1143. return bigBoxes
  1144. }
  1145. /* let getPanoBoxAngleTrend = rowBox => {
  1146. //顺时针方向该pano的box角度范围是越来越大还是越来越小
  1147. let diffs = []
  1148. let angles = rowBox.boxes.map(box => getBbox2Diff(box.bbox2[2], box.bbox2[0]))
  1149. for (let i = 0, j = angles.length; i < j - 1; i++) {
  1150. //得所有相邻之间的差
  1151. let a0 = angles[i],
  1152. a1 = angles[i + 1]
  1153. diffs.push(a1 - a0)
  1154. }
  1155. diffs.sort((a, b) => a - b)
  1156. return diffs[Math.floor(diffs.length / 2)] //中位数
  1157. } */
  1158. /* let getBoxCount = (rowBigBox)=>{
  1159. return rowBigBox.predictBoxCount || rowBigBox.boxes.length
  1160. } */
  1161. let getReverseInfo = (rowBigBox0, rowBigBox1) => {
  1162. //两个row的方向对应
  1163. let reversed = false
  1164. let lefts = [rowBigBox0.left, rowBigBox1.left]
  1165. let rights = [rowBigBox0.right, rowBigBox1.right]
  1166. let dis0 = lefts[0].btmPos.distanceToSquared(lefts[1].btmPos)
  1167. let dis1 = rights[0].btmPos.distanceToSquared(rights[1].btmPos)
  1168. let dis2 = lefts[0].btmPos.distanceToSquared(rights[1].btmPos)
  1169. let dis3 = rights[0].btmPos.distanceToSquared(lefts[1].btmPos)
  1170. let posLeft2, posRight2
  1171. if (dis0 + dis1 > dis2 + dis3) {
  1172. //距离近的代表是同一端
  1173. reversed = true
  1174. posLeft2 = new THREE.Vector3().addVectors(lefts[0].btmPos, rights[1].btmPos).multiplyScalar(0.5)
  1175. posRight2 = new THREE.Vector3().addVectors(rights[0].btmPos, lefts[1].btmPos).multiplyScalar(0.5)
  1176. } else {
  1177. posLeft2 = new THREE.Vector3().addVectors(lefts[0].btmPos, lefts[1].btmPos).multiplyScalar(0.5)
  1178. posRight2 = new THREE.Vector3().addVectors(rights[0].btmPos, rights[1].btmPos).multiplyScalar(0.5)
  1179. }
  1180. let vec = new THREE.Vector2(posLeft2.x - posRight2.x, posLeft2.z - posRight2.z)
  1181. let k = Math.abs(vec.x / vec.y) //这个算斜率更准,但位置容易偏向一侧(可能用边缘的bbox算会好些?)
  1182. return { reversed, k }
  1183. }
  1184. let searchByRow = (groups, datas) => {
  1185. //先查找row,匹配row,再slice row的方法
  1186. this.matchScoreMap['rowBigBox'] = {}
  1187. let rowInfos = []
  1188. let getCenter = (rowBigBox0, rowBigBox1, ignoreCountMatch) => {
  1189. //获取row间的匹配信息
  1190. //获取bigBox位置。由于一排的盒子比较长,中心方向误差大,所以采用先获取两边位置,再求中点的方法
  1191. //if (rowBigBox0.boxes.length != rowBigBox1.boxes.length && !ignoreCountMatch) return //太难了,不算不一样的情况了
  1192. if (rowBigBox0.sid + '&' + rowBigBox1.sid in rowInfos) {
  1193. return rowInfos[rowBigBox0.sid + '&' + rowBigBox1.sid]
  1194. }
  1195. if (rowBigBox0.boxes.length != rowBigBox1.boxes.length && !ignoreCountMatch) return
  1196. //if (getBoxCount(rowBigBox0) != getBoxCount(rowBigBox1) && getBoxCount(rowBigBox0) != 1 && getBoxCount(rowBigBox1) != 1)return
  1197. if (rowBigBox0.sid == 'pano0-row-1,2,6' && rowBigBox1.sid == 'pano2-row-0,2,6') {
  1198. console.log(4)
  1199. }
  1200. let rowInfo
  1201. if (rowBigBox0.boxes.length > 1 && rowBigBox1.boxes.length > 1) {
  1202. //多对多,可以求两端的位置
  1203. let lefts = [rowBigBox0.left, rowBigBox1.left]
  1204. let rights = [rowBigBox0.right, rowBigBox1.right]
  1205. let leftInfo
  1206. let rightInfo
  1207. let info2 = getReverseInfo(rowBigBox0, rowBigBox1)
  1208. let len0 = rowBigBox0.predictLen, //长度应该接近
  1209. len1 = rowBigBox1.predictLen
  1210. let overLen = Math.abs(len0 - len1) /* / (rowBigBox0.boxes.length + rowBigBox1.boxes.length) * 5 */
  1211. if (overLen > 1) {
  1212. console.warn('overLen> 1', overLen, rowBigBox0.sid, '和', rowBigBox1.sid)
  1213. return done()
  1214. }
  1215. if (info2.reversed) {
  1216. leftInfo = getMatchScore(lefts[0], rights[1], { isSingle: true })
  1217. rightInfo = getMatchScore(rights[0], lefts[1], { isSingle: true })
  1218. } else {
  1219. leftInfo = getMatchScore(lefts[0], lefts[1], { isSingle: true })
  1220. rightInfo = getMatchScore(rights[0], rights[1], { isSingle: true })
  1221. }
  1222. let posLeft = getBoxPos(leftInfo)
  1223. let posRight = getBoxPos(rightInfo)
  1224. if (!posLeft || !posRight || leftInfo.score < -4000 || rightInfo.score < -4000) {
  1225. return done() //漫游点重合、>180度会导致此问题
  1226. }
  1227. preDealBox(leftInfo)
  1228. //getBoxSize(leftInfo)
  1229. preDealBox(rightInfo)
  1230. //getBoxSize(rightInfo)
  1231. posLeft = getBoxPos(leftInfo)
  1232. posRight = getBoxPos(rightInfo)
  1233. //验证是否是垂直或水平
  1234. let vec = new THREE.Vector2(posLeft.x - posRight.x, posLeft.z - posRight.z)
  1235. let k = Math.abs(vec.x / vec.y)
  1236. if ((info2.k > 1 && k < 1) || (info2.k < 1 && k > 1)) {
  1237. console.error('请检查!info2.k > 1 && k < 1 || info2.k < 1 && k > 1', rowBigBox0.sid, '和', rowBigBox1.sid) //绘制的方向错误,尺寸错误
  1238. return done()
  1239. }
  1240. let wrongK = 0
  1241. if ((rowBigBox0.k > 1 && rowBigBox1.k < 1) || (rowBigBox0.k < 1 && rowBigBox1.k > 1)) {
  1242. wrongK = rowBigBox0.k / rowBigBox1.k
  1243. if (wrongK < 1) wrongK = 1 / wrongK
  1244. }
  1245. /*
  1246. let trend0 = getPanoBoxAngleTrend(rowBigBox0)
  1247. let trend1 = getPanoBoxAngleTrend(rowBigBox1)
  1248. let judgeReverse = () => { //这个方法有时不准
  1249. let disLeftSquared0 = new THREE.Vector2(posLeft.x - rowBigBox0.pano.position.x, posLeft.z - rowBigBox0.pano.position.z).lengthSq()
  1250. let disRightSquared0 = new THREE.Vector2(posRight.x - rowBigBox0.pano.position.x, posRight.z - rowBigBox0.pano.position.z).lengthSq()
  1251. let a = trend0 * (disLeftSquared0 - disRightSquared0)
  1252. if (a < 0 && Math.abs(a) > 0.1) return true
  1253. let posLeft2 = reversed ? posRight : posLeft, //反向过的对第二个漫游点来说左右是反的
  1254. posRight2 = reversed ? posLeft : posRight
  1255. let disLeftSquared1 = new THREE.Vector2(posLeft2.x - rowBigBox1.pano.position.x, posLeft2.z - rowBigBox1.pano.position.z).lengthSq()
  1256. let disRightSquared1 = new THREE.Vector2(posRight2.x - rowBigBox1.pano.position.x, posRight2.z - rowBigBox1.pano.position.z).lengthSq()
  1257. let b = trend1 * (disLeftSquared1 - disRightSquared1)
  1258. if (b < 0 && Math.abs(b) > 0.1) return true
  1259. }
  1260. if (leftInfo.score < -2000 || rightInfo.score < -2000 || judgeReverse()) {
  1261. //反向试试
  1262. leftInfo = getMatchScore(lefts[0], rights[1], { isSingle: true })
  1263. rightInfo = getMatchScore(rights[0], lefts[1], { isSingle: true })
  1264. posLeft = getBoxPos(leftInfo)
  1265. posRight = getBoxPos(rightInfo)
  1266. reversed = true //rowBigBox1 反向了
  1267. }
  1268. if (leftInfo.score < -2000 || rightInfo.score < -2000 || judgeReverse()) {
  1269. return console.log('getCenter ;两个方向都不符合', rowBigBox0.sid, rowBigBox1.sid)
  1270. } */
  1271. /*const maxK = Math.max(0.6 / Math.sqrt(rowBigBox0.boxes.length), 0.2) // 最大斜率
  1272. if (k < maxK && k > 1 / maxK) {
  1273. return //console.log('放弃,斜率', k)
  1274. } */
  1275. //横的话,按x从小到大,竖的按z从小到大
  1276. if ((k < 1 && posLeft.z > posRight.z) || (k > 1 && posLeft.x > posRight.x)) {
  1277. let temp = posRight
  1278. ;(posRight = posLeft), (posLeft = temp)
  1279. }
  1280. //addLabel(posLeft, 'left-' + rowBigBox0.pano.id + '&' + rowBigBox1.pano.id, { a: 0.1 })
  1281. //addLabel(posRight, 'right-' + rowBigBox0.pano.id + '&' + rowBigBox1.pano.id, { a: 0.1 })
  1282. /* if (rowBigBox0.pano.id + '&' + rowBigBox1.pano.id == '22&26') {
  1283. console.log(777)
  1284. } */
  1285. /* var line1 = LineDraw.createLine([posLeft, posRight])
  1286. meshGroup.add(line1) */
  1287. //根据btmPos矫正一下中心位置, 否则容易偏漫游点这一侧
  1288. let center = new THREE.Vector3().addVectors(posLeft, posRight).multiplyScalar(0.5)
  1289. center
  1290. .add(rowBigBox0.btmPos)
  1291. .add(rowBigBox1.btmPos)
  1292. .multiplyScalar(1 / 3)
  1293. let axis = k > 1 ? 'z' : 'x'
  1294. //posLeft[axis] = center[axis], posRight[axis] = center[axis]
  1295. let match = getMatchScore(rowBigBox0, rowBigBox1, { isSingle: true, center }) //是否预先传送center ?
  1296. //rowInfo.minAngs = [leftInfo.minAng , rightInfo.minAng]
  1297. if (match.name == 'pano4-row-6,4,1,3&pano0-row-0,1,4,5') {
  1298. console.log(8)
  1299. }
  1300. let sc = match.score - overLen * 1000 - wrongK * 100 + leftInfo.score + rightInfo.score
  1301. if (sc < -4000) {
  1302. console.log('放弃,匹配分过低,可能不是一组', rowBigBox0.sid, '和', rowBigBox1.sid, sc)
  1303. return done()
  1304. }
  1305. //console.log('getcenter', rowBigBox0.sid, '和', rowBigBox1.sid, overLen, match.score + overLen * 1000 + leftInfo.score + rightInfo.score)
  1306. rowInfo = {
  1307. rowBigBox0,
  1308. rowBigBox1,
  1309. match,
  1310. k,
  1311. posLeft,
  1312. posRight,
  1313. score: sc / 3 + 500, //700 + match.score*0.7 + (leftInfo.score + rightInfo.score)*0.3 ,
  1314. reversed: info2.reversed,
  1315. }
  1316. } else {
  1317. if (rowBigBox0.boxes.length == 1 && rowBigBox1.boxes.length == 1) {
  1318. rowInfo = getMatchScore(rowBigBox0.boxes[0], rowBigBox1.boxes[0] /* , { isSingle: true } */) //直接匹配box
  1319. } else {
  1320. //一对多。getMatchScore计算误差大(长度越长中心误差越大、宽度计算也误差大)所以再写点限制。直接使用btm来预测长度和位置似乎更准
  1321. let mulBoxRow = rowBigBox0.boxes.length > 1 ? rowBigBox0 : rowBigBox1
  1322. let singleBox = rowBigBox0.boxes.length == 1 ? rowBigBox0 : rowBigBox1
  1323. /* if(rowBigBox0.sid == "pano12-row-3" && rowBigBox1.sid == "pano0-row-3,1,0" ){
  1324. console.log(5)
  1325. } */
  1326. rowInfo = getMatchScore(rowBigBox0, rowBigBox1, { dontCheckDis: true }) //一对多
  1327. rowInfo.k = mulBoxRow.k
  1328. if (rowInfo.center) {
  1329. rowInfo.center.add(getBoxPos(mulBoxRow)).multiplyScalar(0.5)
  1330. }
  1331. if (rowInfo.name == 'pano6-row-2&pano4-row-4,6,3') {
  1332. addLabel(rowInfo.center, 'c')
  1333. }
  1334. rowInfo.predictSize = rowInfo.k > 1 ? { x: mulBoxRow.predictLen, y: 0.6 } : { y: mulBoxRow.predictLen, x: 0.6 }
  1335. //单个的应该和多个的其中一端一样,且是离单个漫游点近的那端(也就是要走到箱子一端看不见其他箱子才行)
  1336. let dis0 = getBoxPos(mulBoxRow.left).distanceToSquared(singleBox.pano.position)
  1337. let dis1 = getBoxPos(mulBoxRow.right).distanceToSquared(singleBox.pano.position)
  1338. let near = dis0 < dis1 ? mulBoxRow.left : mulBoxRow.right
  1339. let dis = getBoxPos(near).distanceToSquared(getBoxPos(singleBox))
  1340. rowInfo.score -= dis * 1000
  1341. }
  1342. }
  1343. function done(rowInfo) {
  1344. rowInfo && rowInfos.push(rowInfo)
  1345. rowInfos[rowBigBox0.sid + '&' + rowBigBox1.sid] = rowInfo
  1346. }
  1347. done(rowInfo)
  1348. return rowInfo
  1349. }
  1350. let matchGroups = []
  1351. let allRelations = []
  1352. let getK = info => {
  1353. let k
  1354. if (info.left) {
  1355. let vec = new THREE.Vector2(info.left.x - info.right.x, info.left.z - info.right.z)
  1356. k = Math.abs(vec.x / vec.y)
  1357. } else {
  1358. k = Math.abs(Math.max(info.size.x, 0.6) / Math.max(info.size.z, 0.6))
  1359. }
  1360. return k
  1361. }
  1362. let ignoreCountMatch = groups.filter(e => e.length > 1).length == 1
  1363. let match = searchType => {
  1364. if (searchType == 'second') ignoreCountMatch = true
  1365. for (let i = 0; i < groups.length - 1; i++) {
  1366. let rowBigBoxes_0 = getPanoBigRowBox(groups[i])
  1367. let pano0 = groups[i][0].pano
  1368. if (searchType == 'second') rowBigBoxes_0 = rowBigBoxes_0.filter(e => !matchGroups.some(u => u.includes(e)))
  1369. for (let j = i + 1; j < groups.length; j++) {
  1370. let rowBigBoxes_1 = getPanoBigRowBox(groups[j])
  1371. if (searchType == 'second') rowBigBoxes_1 = rowBigBoxes_1.filter(e => !matchGroups.some(u => u.includes(e)))
  1372. let pano1 = groups[j][0].pano
  1373. let resultPairs = []
  1374. let bigBoxes_0, bigBoxes_1
  1375. if (rowBigBoxes_0.length < rowBigBoxes_1.length) {
  1376. bigBoxes_0 = rowBigBoxes_1.slice()
  1377. bigBoxes_1 = rowBigBoxes_0.slice()
  1378. } else {
  1379. bigBoxes_0 = rowBigBoxes_0.slice()
  1380. bigBoxes_1 = rowBigBoxes_1.slice()
  1381. }
  1382. while (bigBoxes_1.length < bigBoxes_0.length) {
  1383. bigBoxes_1.push({ sid: 'void' }) //为了使排列正确,补个空,使左右两边个数相等,过后和void匹配的不会计算box
  1384. }
  1385. if (!bigBoxes_0[0]) continue
  1386. searchPair(bigBoxes_0[0], bigBoxes_0, bigBoxes_1, null, resultPairs)
  1387. resultPairs = resultPairs.map(pairs => {
  1388. let infos = pairs.map(pair => (pair.some(e => e.sid == 'void') ? null : getCenter(pair[0], pair[1], ignoreCountMatch)))
  1389. //infos.sort((a,b)=>{return a.score-b.score});
  1390. let score = infos.reduce((s, e) => {
  1391. return s + (e && e.score > -2000 ? e.score : -1000) //只考虑组成功的分数
  1392. }, 0)
  1393. return {
  1394. pairs,
  1395. infos,
  1396. score,
  1397. name: pairs.map(pair => pair.map(item => item.sid).join(' & ')),
  1398. }
  1399. })
  1400. resultPairs.sort((a, b) => b.score - a.score)
  1401. /* if (resultPairs[0].name[0].includes('pano8') && resultPairs[0].name[0].includes('pano0')) {
  1402. console.log(111)
  1403. } */
  1404. resultPairs[0].pairs.forEach((pair, i) => {
  1405. let info = resultPairs[0].infos[i]
  1406. if (info && info.score > -2000) {
  1407. allRelations.push(info)
  1408. let items = pair.filter(e => e.sid != 'void')
  1409. common.pushToGroupAuto(items, matchGroups, null, atGroup => {
  1410. //需要朝向一致才行
  1411. if (!info.k) return true //(box识别的宽高识别不准所以不需要)
  1412. let onePair = atGroup.relationships[0]
  1413. let name = onePair[0].sid + '&' + onePair[1].sid
  1414. if (!rowInfos[name].k) return true //不过不应该有这种情况,否则匹配不到一起才对
  1415. if ((rowInfos[name].k < 1 && info.k < 1) || (rowInfos[name].k > 1 && info.k > 1)) {
  1416. return true
  1417. } else {
  1418. console.log('k不一致无法匹配', info, atGroup)
  1419. }
  1420. })
  1421. //根据目前的规则应该是有端点的和有端点的匹配,box和box匹配
  1422. }
  1423. })
  1424. //console.log(resultPairs[0])
  1425. }
  1426. }
  1427. }
  1428. match()
  1429. ignoreCountMatch || match('second') //再次将剩余的匹配一下,这次允许个数不同的row匹配
  1430. console.log('matchGroups', matchGroups)
  1431. //识别出来的多组,可能有重复的,因为box个数不同所以才没到一组
  1432. //整理一下,每个组整理出一个info,同时重新检查一下,挑去每组中和其他成员非常不同的
  1433. let groupInfo = []
  1434. let getGroupInfo = group => {
  1435. let left = new THREE.Vector3(),
  1436. right = new THREE.Vector3(),
  1437. pointsLen = 0
  1438. let bigBoxes = []
  1439. let info = {}
  1440. group.relationships.forEach(pair => {
  1441. let name = pair[0].sid + '&' + pair[1].sid
  1442. let matchInfo = rowInfos[name] //this.matchScoreMap["rowBigBox"][name] || this.matchScoreMap["cabinet"][name];
  1443. if (matchInfo.posLeft) {
  1444. left.add(matchInfo.posLeft), right.add(matchInfo.posRight), pointsLen++
  1445. } else {
  1446. bigBoxes.push(matchInfo)
  1447. preDealBox(matchInfo)
  1448. getBoxSize(matchInfo)
  1449. }
  1450. })
  1451. let index = groupInfo.length
  1452. if (pointsLen > 0) {
  1453. left.multiplyScalar(1 / pointsLen)
  1454. right.multiplyScalar(1 / pointsLen)
  1455. //addLabel(left, 'Left' + index, { bgcolor: '#F00', a: 0.2 })
  1456. //addLabel(right, 'Right' + index, { bgcolor: '#F00', a: 0.2 })
  1457. let center = new THREE.Vector3().addVectors(left, right).multiplyScalar(0.5)
  1458. //addLabel(center, 'center' + index, { bgcolor: '#F00', a: 0.3 })
  1459. ;(info.left = left), (info.right = right), (info.center = center)
  1460. info.pointsLen = pointsLen
  1461. }
  1462. if (bigBoxes.length > 0) {
  1463. let getAve = bigBoxes => {
  1464. let center1 = new THREE.Vector3(),
  1465. size = new THREE.Vector3()
  1466. bigBoxes.forEach(box => {
  1467. let center0 = getBoxPos(box)
  1468. center1.add(center0)
  1469. size.add(box.size)
  1470. })
  1471. if (pointsLen > 0) {
  1472. let size0 = new THREE.Vector3(Math.abs(left.x - right.x), size.y, Math.abs(left.z - right.z))
  1473. size.add(size0.multiplyScalar(pointsLen)).multiplyScalar(1 / (pointsLen + bigBoxes.length))
  1474. center1.add(info.center.clone().multiplyScalar(pointsLen)).multiplyScalar(1 / (pointsLen + bigBoxes.length))
  1475. } else {
  1476. size.multiplyScalar(1 / bigBoxes.length)
  1477. center1.multiplyScalar(1 / bigBoxes.length)
  1478. }
  1479. return { center1, size }
  1480. }
  1481. let { center1, size } = getAve(bigBoxes)
  1482. //console.log(center1, size)
  1483. let getScores = (center, size) => {
  1484. //获得相对于center,size的差别分数
  1485. bigBoxes.forEach(box => {
  1486. box.sc = -box.center.distanceToSquared(center1) - size.distanceToSquared(box.size) * 0.5
  1487. })
  1488. }
  1489. getScores(center1, size)
  1490. bigBoxes.sort((a, b) => b.sc - a.sc)
  1491. let midItem = bigBoxes[Math.floor(bigBoxes.length / 2)] //中位数
  1492. getScores(midItem.center, midItem.size)
  1493. const minScore = -8
  1494. let removes = bigBoxes.filter(e => {
  1495. return e.sc < minScore
  1496. })
  1497. if (removes.length) {
  1498. let { newGroups } = common.disconnectGroup(
  1499. removes.map(e => [e.box0, e.box1]),
  1500. matchGroups
  1501. )
  1502. console.log('去除错误数据', removes)
  1503. if (newGroups.length > 1) {
  1504. //分裂成多组了,重新计算
  1505. newGroups.forEach(e => {
  1506. getGroupInfo(e)
  1507. })
  1508. return
  1509. }
  1510. bigBoxes = bigBoxes.filter(e => {
  1511. return e.sc >= minScore
  1512. })
  1513. }
  1514. if (bigBoxes.length) {
  1515. let o = getAve(bigBoxes) //again
  1516. ;(info.center = o.center1), (info.size = o.size)
  1517. }
  1518. }
  1519. info.k = getK(info)
  1520. info.bigBoxes = bigBoxes
  1521. info.group = group
  1522. groupInfo.push(info)
  1523. }
  1524. matchGroups.slice(0).forEach(group => {
  1525. getGroupInfo(group)
  1526. })
  1527. let getLength = c => {
  1528. //获取bigbox长度
  1529. 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
  1530. }
  1531. let getLeft = (group, k) => {
  1532. let dirAxis = (k || group.k) > 1 ? 'x' : 'z'
  1533. return group.left ? group.left[dirAxis] - 0.3 : group.center[dirAxis] - group.size[dirAxis] / 2 //left和right加减半个宽度
  1534. }
  1535. let getRight = (group, k) => {
  1536. let dirAxis = (k || group.k) > 1 ? 'x' : 'z'
  1537. return group.right ? group.right[dirAxis] + 0.3 : group.center[dirAxis] + group.size[dirAxis] / 2
  1538. }
  1539. //识别是否group之间有一样的, 去重
  1540. {
  1541. let realGroups = []
  1542. let getAveWidth = (infos, len) => {
  1543. let boxCounts = []
  1544. infos.forEach(e => {
  1545. boxCounts.push(...e.group.map(bigBox => bigBox.boxes.length))
  1546. })
  1547. /* infos.forEach(e => {
  1548. boxCounts.push(...e.group.relationships.map(pair =>
  1549. Math.max(pair[0].predictBoxCount || pair[0].boxes.length, pair[1].predictBoxCount || pair[1].boxes.length)))
  1550. }) //根据匹配到的来得个数 */
  1551. /* infos.forEach(e => {
  1552. e.group.relationships.forEach(pair => {
  1553. let counts = pair.map(e => e.boxes.length)
  1554. if (counts.filter(e => e == 1).length == 1) {
  1555. //如果是1和其他数字匹配,取数字大的。如1和3的话是3个箱子。
  1556. let c = counts.find(e => e != 1)
  1557. boxCounts.push(c)
  1558. } else {
  1559. boxCounts.push(...counts) //否则两个数字都取
  1560. }
  1561. })
  1562. }) //根据匹配到的来得个数 */
  1563. boxCounts.sort((a, b) => a - b)
  1564. /*let midCounts = [] //这一排的箱子个数中位数
  1565. midCounts.push(boxCounts[Math.floor(boxCounts.length / 2)])
  1566. if (boxCounts.length % 2 == 0) {
  1567. let a = boxCounts[Math.floor(boxCounts.length / 2) - 1]
  1568. let b = midCounts[0]
  1569. let c = b - 1
  1570. while (c >= a) {
  1571. midCounts.push(c)
  1572. c--
  1573. }
  1574. //加入a到b中所有的整数
  1575. } */
  1576. let midCounts = []
  1577. let r0 = 0.3,
  1578. r1 = 0.7 //取中间这部分的算最适合的个数,结果不一定是中位数
  1579. boxCounts.slice(Math.floor(boxCounts.length * r0), Math.floor(boxCounts.length * r1) + 1).forEach(c => {
  1580. if (!midCounts.includes(c)) midCounts.push(c)
  1581. })
  1582. let { min, max } = standards.cabinet.widthNormal
  1583. let standardW = (min + max) / 2
  1584. let aveWs = midCounts.map(e => {
  1585. return { aveW: len / e, count: e }
  1586. })
  1587. aveWs.sort((a, b) => Math.abs(a.aveW - standardW) - Math.abs(b.aveW - standardW))
  1588. let aveW = aveWs[0].aveW
  1589. let count = aveWs[0].count
  1590. if (aveW > max || aveW < min) {
  1591. let w = THREE.MathUtils.clamp(aveW, min, max)
  1592. //console.warn(`box aveW宽度不太对,从${aveW}修改到${w}`)
  1593. aveW = w
  1594. }
  1595. return { aveW, count }
  1596. }
  1597. let getBox2 = (center, len, thick, k) => {
  1598. let box2 = new THREE.Box2()
  1599. box2.expandByPoint(new THREE.Vector2(center.x, center.z))
  1600. let sizeVec = k > 1 ? new THREE.Vector2(len / 2, thick / 2) : new THREE.Vector2(thick / 2, len / 2)
  1601. box2.expandByVector(sizeVec)
  1602. return box2
  1603. }
  1604. const standardW = 0.6 //两排之间最小距离
  1605. /* let getBoxLen = (group)=>{
  1606. if( group.bigBoxes.length == 0) return 0
  1607. let max = 0
  1608. group.bigBoxes.forEach(e=>{
  1609. max = Math.max(max, e.box0.boxes ? e.box0.boxes.length : 1 , e.box1.boxes ? e.box1.boxes.length : 1 )
  1610. })
  1611. return max
  1612. } */
  1613. for (let m = 0; m < groupInfo.length - 1; m++) {
  1614. let group0 = groupInfo[m]
  1615. for (let n = m + 1; n < groupInfo.length; n++) {
  1616. let group1 = groupInfo[n]
  1617. /* if(group0.k == 5.135329840006164 && group1.k ==4.494597962707433 || group0.k ==4.494597962707433 && group1.k == 5.135329840006164){
  1618. console.log(4)
  1619. } */
  1620. if (group0.k == 4.242560016595383 || group1.k == 0.8571428571428572) {
  1621. console.log(2)
  1622. }
  1623. const maxR = 2.3
  1624. if (
  1625. ((group0.k > 1 && group1.k < 1) || (group0.k < 1 && group1.k > 1)) &&
  1626. //getBoxLen(group0) != 1 && getBoxLen(group1) != 1 )continue //且没有其中一个是单个的box
  1627. //(group0.k > maxR || group0.k < 1/maxR ) && (group1.k > maxR || group1.k < 1/maxR )) continue //如果是方块状的无视k
  1628. getLength(group0) > 1.5 &&
  1629. getLength(group1) > 1.5
  1630. )
  1631. continue //如果是方块状的无视k
  1632. //间距
  1633. let spaceAxis = (group0.k + group1.k) / 2 > 1 ? 'z' : 'x'
  1634. let spaceDis = Math.abs(group0.center[spaceAxis] - group1.center[spaceAxis])
  1635. if (spaceDis > standardW * 1.5) continue
  1636. let o0 = getAveWidth([group0], getLength(group0)) //因为有可能长度和箱子个数不匹配,所以需要得到限制后的宽度再比较
  1637. let o1 = getAveWidth([group1], getLength(group1))
  1638. let len0 = (group0.predictLen = o0.aveW * o0.count)
  1639. let len1 = (group1.predictLen = o1.aveW * o1.count)
  1640. const minR = 0.5 //不可限制太死,因为有的框个数识别少了,导致len短。但可通过重叠面积来判断
  1641. // if( len0 / len1 < minR || len0 / len1 > 1/minR) continue
  1642. let area0 = (group0.area = len0 * o0.aveW)
  1643. let area1 = (group1.area = len1 * o1.aveW)
  1644. let getBoxMixArea = (expandRatio1, expandRatio2) => {
  1645. let box0 = getBox2(group0.center, len0 + expandRatio1, o0.aveW + expandRatio2, group0.k)
  1646. let box1 = getBox2(group1.center, len1 + expandRatio1, o1.aveW + expandRatio2, group1.k)
  1647. let mixBox = getMixBox(box0, box1) //重叠部分
  1648. let s = mixBox.getSize(new THREE.Vector2())
  1649. return { box0, box1, areaMix: Math.max(0, s.x) * Math.max(0, s.y) } //可能是0
  1650. }
  1651. let areaMixExpand = getBoxMixArea(0.1, 0.4).areaMix
  1652. if (areaMixExpand / area0 < 0.7 && areaMixExpand / area1 < 0.7) continue //包含的可以通过
  1653. let areaMix = getBoxMixArea(0, 0).areaMix //实际重合面积
  1654. group0.contains = group0.contains || []
  1655. group1.contains = group1.contains || []
  1656. group0.contains.push({ group: group1, selfPercent: areaMix / area0, percent2: areaMix / area1, areaMix })
  1657. group1.contains.push({ group: group0, selfPercent: areaMix / area1, percent2: areaMix / area0, areaMix })
  1658. console.log('两个合并', group0, group1)
  1659. common.pushToGroupAuto([group0, group1], realGroups)
  1660. //包含的直接合并吧 - - ,这样会使结果偏移,不过没办法了,多个重叠面积太难算了
  1661. }
  1662. }
  1663. //但没合并前样本数量少,包含关系可能有错 - -
  1664. /*for(let m=0; m<groupInfo.length;m++){
  1665. let group = groupInfo[m]
  1666. let contains = group.contains.filter(e=> e.percent2 > 0.8) //所有包含的
  1667. contains.reduce
  1668. } */
  1669. groupInfo.forEach(info => {
  1670. //加入单个的
  1671. if (!realGroups.some(groups => groups.includes(info))) {
  1672. realGroups.push([info])
  1673. }
  1674. })
  1675. console.log('realGroups', realGroups)
  1676. //get boxes
  1677. realGroups.forEach((infos, i) => {
  1678. const sampleCount = infos.reduce((w, c) => {
  1679. return (w += c.pointsLen || c.bigBoxes.length)
  1680. }, 0)
  1681. let k
  1682. {
  1683. //const k = infos.reduce((w, c) => (w += c.k), 0) / infos.length
  1684. let ks = infos.map(e => e.k)
  1685. ks.sort((a, b) => a - b)
  1686. let min = ks[0],
  1687. max = ks[ks.length - 1]
  1688. if (min < 1 && max > 1) {
  1689. //比较最小和最大,选取更极端的那个
  1690. let min_ = 1 / min
  1691. if (min_ < max) k = max
  1692. else k = min
  1693. } else k = (min + max) / 2
  1694. }
  1695. let centerPos = infos
  1696. .reduce((w, c) => {
  1697. return w.add(c.center.clone().multiplyScalar(c.pointsLen || c.bigBoxes.length))
  1698. }, new THREE.Vector3())
  1699. .multiplyScalar(1 / sampleCount) //预得中心点
  1700. //获取左右端点(需要排除可能的误差,所以采用最靠近端点的三个点。但无法排除前三个点中万一含有包含box的、或者误差大的端点)
  1701. let lefts = infos
  1702. .map(e => getLeft(e, k))
  1703. .sort((a, b) => a - b)
  1704. .filter(a => a < centerPos[k > 1 ? 'x' : 'z'])
  1705. .slice(0, 3)
  1706. let rights = infos
  1707. .map(e => getRight(e, k))
  1708. .sort((a, b) => b - a)
  1709. .filter(a => a > centerPos[k > 1 ? 'x' : 'z'])
  1710. .slice(0, 3)
  1711. let left = 0,
  1712. right = 0
  1713. let c0 = ((lefts.length + 1) * lefts.length) / 2
  1714. lefts.forEach((e, i) => {
  1715. //越靠近最外侧权重越高。
  1716. left += e * ((lefts.length - i) / c0)
  1717. })
  1718. c0 = ((rights.length + 1) * rights.length) / 2
  1719. rights.forEach((e, i) => {
  1720. right += e * ((rights.length - i) / c0)
  1721. })
  1722. centerPos[k > 1 ? 'x' : 'z'] = (left + right) / 2
  1723. let len = right - left //加一点值是因为之前计算长度,用的是最外box的中心点,会少box一半宽度
  1724. let infos2 = infos.filter(e => {
  1725. return !e.predictLen || e.predictLen / len > 0.7
  1726. })
  1727. if (infos2.length == 0) {
  1728. infos2 = infos.sort((a, b) => b.predictLen - a.predictLen).slice(0, 1)
  1729. }
  1730. let { aveW, count } = getAveWidth(infos2, len)
  1731. //长宽比中心点的误差更大,尤其是box类型的、或样本少的
  1732. //获取高度
  1733. let heights = []
  1734. {
  1735. let pairs = [],
  1736. heightss
  1737. /* infos.forEach(e => {
  1738. pairs.push(...e.group.relationships.filter(pair => pair[0].boxes.length == count && pair[1].boxes.length == count))
  1739. })
  1740. if (pairs.length) {
  1741. heightss = pairs.map(pair => {
  1742. let boxes = pair.map(e => {
  1743. return e.boxes.slice()
  1744. })
  1745. let match = rowInfos[pair[0].sid + '&' + pair[1].sid]
  1746. let ifReverse = match.reversed
  1747. if (match.reversed == void 0 && pair[0].boxes.length > 1 && pair[1].boxes.length > 1) {
  1748. let { reversed } = getReverseInfo(pair[0], pair[1])
  1749. ifReverse = reversed
  1750. }
  1751. if (ifReverse) {
  1752. boxes[1].reverse()
  1753. }
  1754. let heights1 = []
  1755. let topPoss = []
  1756. for (let i = 0; i < count; i++) {
  1757. let match1 = getMatchScore(boxes[0][i], boxes[1][i], { onlyGet: true })
  1758. let topPos = match1 && match1.topPos
  1759. if (!topPos) {
  1760. topPos = getBoxTop({ box0: boxes[0][i], box1: boxes[1][i] })
  1761. }
  1762. heights1.push(topPos.y - groundY)
  1763. if (topPos.y - groundY < 0) {
  1764. console.log('?')
  1765. }
  1766. topPoss.push(topPos)
  1767. }
  1768. if ((k < 1 && topPoss[0].z > topPoss[count - 1].z) || (k > 1 && topPoss[0].x > topPoss[count - 1].x)) {
  1769. heights1.reverse()
  1770. }
  1771. return heights1
  1772. })
  1773. } else { */
  1774. let bigBoxes = []
  1775. infos.forEach(e => {
  1776. bigBoxes.push(...e.group.filter(e => e.boxes.length == count))
  1777. })
  1778. heightss = bigBoxes.map(bigBox => {
  1779. let topPoss = bigBox.boxes.map(box => {
  1780. let a = { box0: box }
  1781. getBoxTop(a)
  1782. return a.topPos
  1783. })
  1784. if ((k < 1 && topPoss[0].z > topPoss[count - 1].z) || (k > 1 && topPoss[0].x > topPoss[count - 1].x)) {
  1785. topPoss.reverse()
  1786. }
  1787. let heights1 = topPoss.map(topPos => topPos.y - groundY)
  1788. return heights1
  1789. })
  1790. //}
  1791. heightss.forEach(arr => {
  1792. for (let i = 0; i < count; i++) {
  1793. heights[i] = (heights[i] || 0) + arr[i]
  1794. }
  1795. })
  1796. heights = heights.map(e => {
  1797. let h = e / heightss.length
  1798. return h
  1799. })
  1800. //console.log('heightss',heightss, pairs, heights)
  1801. }
  1802. //拆分成小box
  1803. let size = new THREE.Vector3(aveW, 2, aveW)
  1804. let c = 0
  1805. infos.box = []
  1806. while (c < count) {
  1807. let center
  1808. if (k > 1) {
  1809. let startX = centerPos.x - ((count - 1) / 2) * aveW
  1810. center = new THREE.Vector3(startX + c * aveW, centerPos.y, centerPos.z)
  1811. } else {
  1812. let startZ = centerPos.z - ((count - 1) / 2) * aveW
  1813. center = new THREE.Vector3(centerPos.x, centerPos.y, startZ + c * aveW)
  1814. }
  1815. let size1 = heights[c] ? size.clone().setY(heights[c]) : size //如1*3的是得不到height的
  1816. let box = new Box({ name: 'row' + i + '-' + c, center, size: size1, boxType: 'cabinet', infos })
  1817. c++
  1818. infos.box.push(box)
  1819. }
  1820. })
  1821. return realGroups.length > 0
  1822. }
  1823. }
  1824. let removeContain = arr => {
  1825. //去除嵌套
  1826. let len = arr.length
  1827. if (len < 2) return
  1828. for (let i = 0; i < len - 1; i++) {
  1829. let box0 = arr[i]
  1830. getBoxBase(box0)
  1831. box0.contains = box0.contains || []
  1832. for (let j = i + 1; j < len; j++) {
  1833. let box1 = arr[j]
  1834. getBoxBase(box1)
  1835. box1.contains = box1.contains || []
  1836. let d3 = Math.abs(box1.bbox2CenterX - box0.bbox2CenterX) //限制d3是因为在相差180度两端可能也符合
  1837. //d4 = Math.abs(box1.bbox2[3] - box0.bbox2[3])
  1838. if (d3 > 0.4 /* || d4 > 0.01 */) continue
  1839. let d0 = getBbox2Diff(box1.bbox2[0], box0.bbox2[0]),
  1840. d1 = getBbox2Diff(box0.bbox2[2], box1.bbox2[2])
  1841. let min = 0.005
  1842. if ((d1 >= 0 && Math.abs(d0) < min) || (d0 >= 0 && Math.abs(d1) < min) || (d1 >= 0 && d0 >= 0)) {
  1843. box0.contains.push(box1)
  1844. } else if ((d0 <= 0 && Math.abs(d1) < min) || (d1 <= 0 && Math.abs(d0) < min) || (d1 <= 0 && d0 <= 0)) {
  1845. box1.contains.push(box0)
  1846. }
  1847. }
  1848. }
  1849. let getWidthScore = (box, type) => {
  1850. const addDis = 0.1 //因为用的是btm的pos,比中心点近了一些,所以加上一段距离
  1851. let o = getBoxPoseByPos(box, getBoxPos(box), addDis)
  1852. let boxPjW = o.projectWidth
  1853. let standardPjW = (o.maxProjectWidth + o.minProjectWidth) / 2
  1854. let s = type == 'out' ? boxPjW - standardPjW : standardPjW - boxPjW
  1855. return -Math.pow(s, 2) * 10
  1856. }
  1857. arr.slice().forEach(box => {
  1858. if (box.contains.length > 1) {
  1859. //假设不存在第二层嵌套, 假设每个只能被一个嵌套
  1860. //决定留大还是留小
  1861. //先只去掉包含两个以上的,且角度范围一致
  1862. //尽量保留内层,除非内层太小
  1863. let { leftX, rightX } = getLeftRight(box.contains)
  1864. if (Math.abs(getBbox2Diff(box.bbox2[0], leftX)) > 0.005 || Math.abs(getBbox2Diff(box.bbox2[2], rightX)) > 0.005) return //范围不一致
  1865. let remainChild = true
  1866. let childrenScores = box.contains.map(e => getWidthScore(e, 'in'))
  1867. let childAve = childrenScores.reduce((w, c) => w + c, 0) / childrenScores.length
  1868. if (childAve < -4) {
  1869. let outScore = getWidthScore(box, 'out')
  1870. remainChild = childAve > outScore
  1871. }
  1872. if (!remainChild) {
  1873. box.contains.forEach(e => {
  1874. ;(e.state = '因被嵌套被删除'), (e.containBy = box)
  1875. arr.splice(arr.indexOf(e), 1)
  1876. console.log('因被嵌套被删除', ...box.contains)
  1877. })
  1878. } else {
  1879. box.state = '因嵌套其他被删除'
  1880. console.log('因嵌套其他被删除', box)
  1881. arr.splice(arr.indexOf(box), 1)
  1882. }
  1883. }
  1884. })
  1885. }
  1886. let waitFindRest = []
  1887. let Search = type => {
  1888. console.error('开始search', type)
  1889. let matchScoreMap = (this.matchScoreMap[type] = {})
  1890. let datas = {}
  1891. let panoIds = []
  1892. for (let id in this.datas) {
  1893. datas[id] = this.datas[id].shapes.filter(e => e.category == type)
  1894. datas[id].length && panoIds.push(id)
  1895. }
  1896. for (let id in this.datas) {
  1897. //对data预处理
  1898. //(之后如果还出现不同类型重叠在一起的,需要先识别摘除下。 )4GqaqNdyjGf
  1899. removeContain(datas[id]) //去除线框中的嵌套,主要是一个嵌套两个的。案例:KK-1Zjm9Rbl47
  1900. if (datas[id].length) {
  1901. //融合。很多box被一分为二了,基本都是在全景图左右边界处。
  1902. let bigBoxes = getPanoBigRowBox(datas[id], { reason: 'mix' })
  1903. bigBoxes.forEach(bigBox => {
  1904. if (bigBox.boxes.length > 1) {
  1905. bigBox.boxes.forEach(box => {
  1906. ;(box.state = '被删除'), (box.mixTo = bigBox)
  1907. let i = datas[id].indexOf(box)
  1908. datas[id].splice(i, 1)
  1909. if (version == 'vision') {
  1910. i = this.datasMixed[id].shapes.findIndex(e => e.sid == box.sid)
  1911. this.datasMixed[id].shapes.splice(i, 1)
  1912. }
  1913. })
  1914. console.log('因融合而删除', bigBox.boxes)
  1915. datas[id].push(bigBox)
  1916. if (version == 'vision') {
  1917. this.datasMixed[id].shapes.push(bigBox)
  1918. }
  1919. let shapes = this.datas[id].shapes
  1920. bigBox.index = shapes.length > 1 ? shapes[shapes.length - 2].index + 1 : 0
  1921. {
  1922. let a = bigBox.sid.split('mix-')
  1923. bigBox.sid = a[0] + bigBox.index + '(mix' + a[1] + ')' //"pano20-mix-1,2"
  1924. }
  1925. bigBox.category = type //更正
  1926. }
  1927. })
  1928. }
  1929. }
  1930. if (panoIds.length == 0) return
  1931. panoIds.sort((a, b) => {
  1932. return datas[b].length - datas[a].length
  1933. })
  1934. let groups = panoIds.map(e => datas[e])
  1935. console.log('按box个数排序:', groups.slice())
  1936. let group0 = groups[0],
  1937. len0 = group0.length
  1938. if (groups.length == 1) {
  1939. //只有一个全景里有数据
  1940. group0.forEach(e => createSinglePano(e))
  1941. return combines(type)
  1942. }
  1943. if (len0 == 1) {
  1944. //最多的也只有一个box。此情况大部分是空调
  1945. panoIds.forEach(e => getBoxBase(datas[e][0]))
  1946. let maxAngle
  1947. //找出centerDir夹角最大的两个pano
  1948. for (let i = 0; i < panoIds.length; i++) {
  1949. let box0 = datas[panoIds[i]][0]
  1950. for (let j = i + 1; j < panoIds.length; j++) {
  1951. let box1 = datas[panoIds[j]][0]
  1952. getMatchScore(box0, box1, { isSingle: true })
  1953. }
  1954. }
  1955. let list = Object.keys(matchScoreMap)
  1956. list.sort((a, b) => {
  1957. return matchScoreMap[b].score - matchScoreMap[a].score
  1958. })
  1959. let match = matchScoreMap[list[0]]
  1960. preDealBox(match)
  1961. if (match.score > -100) {
  1962. getBoxSize(match)
  1963. if (match.score > 0 && match.sizeAdjust < 0.1) {
  1964. new Box(matchScoreMap[list[0]])
  1965. waitFindRest.push({ type, args: [groups] }) //等待最后检查遗漏
  1966. return
  1967. }
  1968. }
  1969. //根据分数重排序,前两个已匹配的pano放在第一第二(reMatchLowScores会跳过),获得groups2
  1970. let panoIds2 = []
  1971. list.forEach(e => {
  1972. let info = matchScoreMap[e]
  1973. if (!panoIds2.includes(info.box0.pano.id)) panoIds2.push(info.box0.pano.id)
  1974. if (!panoIds2.includes(info.box1.pano.id)) panoIds2.push(info.box1.pano.id)
  1975. })
  1976. let groups2 = panoIds2.map(e => datas[e])
  1977. //继续match
  1978. reMatchLowScores([match], groups2)
  1979. waitFindRest.push({ type, args: [groups2] }) //等待最后检查遗漏
  1980. return
  1981. }
  1982. {
  1983. //重新根据距离排序,挑选离所有box距离最近的两个pano (远的可能看不到box,或者得到的线框计算的位置不准。不过其实太近也不准-,-)
  1984. let counts = {}
  1985. groups.forEach(e => {
  1986. e.forEach(a => getBoxBase(a))
  1987. counts[e.length] || (counts[e.length] = [])
  1988. counts[e.length].push(e)
  1989. })
  1990. groups = []
  1991. let nums = Object.keys(counts)
  1992. nums.reverse()
  1993. nums.forEach(count => {
  1994. let groups_ = counts[count]
  1995. if (groups_.length > 1) {
  1996. groups_.forEach(e => {
  1997. e.disSc = e.reduce((w, c) => {
  1998. let pos = getBoxPos(c)
  1999. return w + c.pano.position.distanceToSquared(pos)
  2000. }, 0)
  2001. })
  2002. groups_.sort((a, b) => a.disSc - b.disSc)
  2003. }
  2004. groups.push(...groups_)
  2005. })
  2006. console.log('按距离和个数排序:', groups)
  2007. group0 = groups[0]
  2008. }
  2009. if (type == 'cabinet') {
  2010. //转化为分组
  2011. if (searchByRow(groups, datas)) {
  2012. waitFindRest.push({ type, args: [groups, 0] }) //等待最后检查遗漏
  2013. return
  2014. }
  2015. }
  2016. //零散匹配。
  2017. let group1 = groups[1],
  2018. len1 = group1.length
  2019. for (let i = 0; i < len0; i++) {
  2020. //复杂度:n的平方次
  2021. for (let j = 0; j < len1; j++) {
  2022. let box1 = group0[i]
  2023. let box2 = group1[j]
  2024. let result = getMatchScore(box1, box2)
  2025. }
  2026. }
  2027. //寻找最佳配对 n!种组合(是否要限制个数多的情况?) 超过8个就很恐怖
  2028. //仅先查找选中的两个pano配对
  2029. let resultPairs = []
  2030. let newGroup0 = group0.slice(0)
  2031. let newGroup1 = group1.slice(0)
  2032. while (newGroup1.length < newGroup0.length) {
  2033. newGroup1.push({ sid: 'void' }) //为了使排列正确,补个空,使左右两边个数相等,过后和void匹配的不会计算box
  2034. }
  2035. searchPair(group0[0], newGroup0, newGroup1, null, resultPairs)
  2036. console.log(
  2037. 'resultPairs',
  2038. resultPairs.map(pairs => pairs.map(pair => pair.map(item => item.sid).join(' & ')))
  2039. )
  2040. resultPairs = resultPairs.map(pairs => {
  2041. let infos = pairs.map(pair => matchScoreMap[pair[0].sid + '&' + pair[1].sid])
  2042. let score = infos.reduce((s, e) => {
  2043. return s + (e ? e.score : 0)
  2044. }, 0)
  2045. //if(infos[0].score < -1000){
  2046. //score -= infos[0].score
  2047. //}
  2048. let o = {
  2049. infos,
  2050. score,
  2051. pairs,
  2052. name: pairs.map(pair => pair.map(item => item.sid).join(' & ')),
  2053. }
  2054. return o
  2055. })
  2056. console.log('resultPairs', resultPairs.slice())
  2057. console.log(
  2058. 'resultPairs按分数高低',
  2059. resultPairs.sort((a, b) => b.score - a.score)
  2060. )
  2061. //console.log('compu',compu)
  2062. let noMatches = [] //和void匹配的,需要和其他pano的重新匹配
  2063. let mayHaventMatched = []
  2064. let lowScores = []
  2065. if (resultPairs[0]) {
  2066. resultPairs[0].infos.forEach((info, i) => {
  2067. if (!info) {
  2068. noMatches.push(resultPairs[0].pairs[i].find(e => e.sid != 'void'))
  2069. return //match with void
  2070. }
  2071. if (info.score < -2000) {
  2072. lowScores.push(info)
  2073. return
  2074. }
  2075. preDealBox(info)
  2076. getBoxSize(info)
  2077. if (info.sizeAdjust > 0.1) {
  2078. lowScores.push(info)
  2079. return
  2080. }
  2081. if (info.box0.category == 'battery' && info.size.x < 0.9 && info.size.z < 0.9) {
  2082. //宽度较小
  2083. let vec0 = new THREE.Vector3().subVectors(info.box0.pano.position, getBoxPos(info))
  2084. let vec1 = new THREE.Vector3().subVectors(info.box1.pano.position, getBoxPos(info))
  2085. if (vec0.x * vec1.x > 0 && vec0.z * vec1.z > 0) {
  2086. //同一个象限(偏向一侧)
  2087. lowScores.push(info)
  2088. return
  2089. }
  2090. }
  2091. let box = new Box(info)
  2092. })
  2093. }
  2094. if (noMatches.length) {
  2095. reMatchLowScores(
  2096. noMatches.map(e => {
  2097. return { box0: e }
  2098. }),
  2099. groups
  2100. )
  2101. }
  2102. reMatchLowScores(lowScores, groups)
  2103. waitFindRest.push({ type, args: [groups] })
  2104. //combines(type)
  2105. }
  2106. function findRest(groups /* ,startIndex=2 */) {
  2107. //查找是否有遗漏。
  2108. //1 可能有距离较远的box不在头两个pano的附近导致被漏掉。(概率很小)
  2109. //2 被剩余的
  2110. let boxes = [],
  2111. map = new Map(),
  2112. bestDisSquared = 2
  2113. groups.forEach(g => {
  2114. boxes.push(...g)
  2115. })
  2116. boxes = boxes.filter(box => !used(box))
  2117. boxes.forEach(box => {
  2118. getBoxBase(box)
  2119. let p1 = new THREE.Vector2(box.pano.position.x, box.pano.position.z)
  2120. let p2 = new THREE.Vector2(box.btmPos.x, box.btmPos.z)
  2121. let dis = p1.distanceToSquared(p2)
  2122. let diff = Math.abs(dis - bestDisSquared)
  2123. map.set(box, diff)
  2124. })
  2125. boxes = boxes.sort((a, b) => map.get(a) - map.get(b)) //将距离最佳的排前面,距离远的得到的位置不准确,也容易被遮
  2126. boxes.forEach(box => {
  2127. if (!used(box)) {
  2128. if (box.sid == 'pano2-4') {
  2129. console.log(3)
  2130. }
  2131. //如果和现有的box的距离都很远,很可能是漏掉的
  2132. let near = boxesSolid.find(solidBox => {
  2133. if (solidBox.name == 'battery-low:pano0-8&pano2-3') {
  2134. console.log(3)
  2135. }
  2136. if (solidBox.boxType != box.type && (solidBox.boxType == 'air-hanging' || box.type == 'air-hanging')) return //挂空调一般不会撞到地面上的
  2137. let p1 = getBoxPos(solidBox)
  2138. let p2 = getBoxPos(box)
  2139. let p1_ = new THREE.Vector2(p1.x, p1.z)
  2140. let p2_ = new THREE.Vector2(p2.x, p2.z)
  2141. let maxWidth = standards[solidBox.boxType].widthNormal.max
  2142. if (solidBox.boxType != box.type) {
  2143. maxWidth = Math.min(standards[box.type].widthNormal.max, maxWidth)
  2144. }
  2145. let dis = solidBox.bound.distanceToPoint(p2)
  2146. let r0 = solidBox.boxType == 'air' ? 2 : solidBox.boxType == 'battery' ? 1.1 : 1 //空调最不容易扎堆放置,所以范围设置广一些
  2147. let r1 = math.linearClamp(box.pano.position.distanceTo(p2), 3, 6, 1, 1.5) //距离远的话识别、计算都会更不准确,给一定的容错
  2148. let ra = (solidBox.boxType == box.type ? 1 : 0.5) * r0 * r1 //数字越小限制越大
  2149. //let rb = (solidBox.boxType == box.type ? 0.5 : 0.2 ) * r0 * r1
  2150. let a = maxWidth * maxWidth * ra - p1_.distanceToSquared(p2_)
  2151. let b = -dis * 0.5
  2152. let c = a + b
  2153. if (c > 0) {
  2154. console.log(1)
  2155. }
  2156. return c > 0
  2157. })
  2158. if (!near) {
  2159. reMatchLowScores([{ box0: box, log: 'findRest' }], groups, 0)
  2160. } else {
  2161. //console.log('find near', near.name, box.sid)
  2162. }
  2163. }
  2164. })
  2165. }
  2166. function used(box) {
  2167. let has = e => {
  2168. return e.box0 == box || e.box1 == box
  2169. }
  2170. return /* matched.includes(box) || */ boxesSolid.some(
  2171. e => /* e.boxType == box.type && */ has(e) || (e.list && e.list.some(a => has(a))) || (e.infos && e.infos.some(u => u.group.some(r => r.boxes.some(b => b == box)))) //row
  2172. )
  2173. }
  2174. function reMatchLowScores(lowScores, groups, startIndex = 2) {
  2175. let matched = [],
  2176. tooLows = []
  2177. let isSameMatch = (match0, match1) => {
  2178. //是否对应同一个box实体(不一定准),通过两两box之间是否都match来判断
  2179. //如果是相同pano但不同的box肯定不是对应同一个box实体
  2180. let ifWrong = (box0, box1) => {
  2181. if (box0 == box1) return
  2182. if (box0.pano == box1.pano) return true
  2183. let match2 = getMatchScore(box0, box1, { isSingle: true, restMatch: true })
  2184. if (match2.score < -2000) return true
  2185. }
  2186. if (ifWrong(match0.box0, match1.box0) || ifWrong(match0.box1, match1.box1) || ifWrong(match0.box0, match1.box1) || ifWrong(match0.box1, match1.box0)) return
  2187. return true
  2188. }
  2189. if (lowScores.length) {
  2190. console.warn(lowScores[0].log || (lowScores[0].box1 ? '低分重新匹配' : '剩余匹配'), ...lowScores)
  2191. if (lowScores[0].box1) {
  2192. lowScores.sort((a, b) => {
  2193. //低分优先
  2194. return a.score - b.score
  2195. })
  2196. }
  2197. lowScores.forEach(info => {
  2198. //info中的box0和box1分别向后寻找其他的配对。选择分数高的配对。 但box0和box1可能是错误配对,会导致找到了替代的也可能遗漏。
  2199. /* if (info.name == 'pano0-3&pano2-3') {
  2200. console.log(1)
  2201. } */
  2202. let box01 = info.box0
  2203. let box02 = info.box1
  2204. let bigGroup = []
  2205. box02 && bigGroup.push(info)
  2206. let got
  2207. for (let cur = startIndex; cur < groups.length; cur++) {
  2208. let thirdGroup = groups[cur]
  2209. let scores0 = [],
  2210. scores1 = []
  2211. thirdGroup.forEach(box1 => {
  2212. //if (matched.includes(box1.sid)) return
  2213. if (used(box1)) return //会不会太严格?
  2214. if (box1.pano != box01.pano) {
  2215. let r1 = getMatchScore(box01, box1, { isSingle: true, restMatch: true })
  2216. r1.score > -4000 && scores0.push(r1)
  2217. }
  2218. if (box02 && box1.pano != box02.pano) {
  2219. let r2 = getMatchScore(box02, box1, { isSingle: true, restMatch: true })
  2220. r2.score > -4000 && scores1.push(r2)
  2221. }
  2222. })
  2223. scores0.sort((a, b) => {
  2224. return b.score - a.score
  2225. })
  2226. scores1.sort((a, b) => {
  2227. return b.score - a.score
  2228. })
  2229. scores0[0] && bigGroup.push(scores0[0])
  2230. scores1[0] && bigGroup.push(scores1[0])
  2231. }
  2232. bigGroup.sort((a, b) => {
  2233. return b.score - a.score
  2234. })
  2235. let goodList = bigGroup.slice(0, 10).map(e => {
  2236. if (!getBoxPos(e)) return e
  2237. preDealBox(e)
  2238. getBoxSize(e)
  2239. return e
  2240. })
  2241. let goodList2 = goodList
  2242. .sort((a, b) => {
  2243. return b.score - a.score
  2244. })
  2245. .slice(0, 3)
  2246. if (goodList2.length == 0) {
  2247. return createSinglePano(box01)
  2248. }
  2249. if (goodList2[0].score > -1200) {
  2250. goodList2 = goodList2.filter(e => e.score > -1200)
  2251. } else {
  2252. goodList2 = [goodList2[0]] // 最高分已经过小
  2253. if (goodList2[0].score < -1500) {
  2254. if (!box02) {
  2255. if (info.log == 'findRest' || box01.btmPos.distanceTo(box01.pano.position) < 2.5) {
  2256. //远距离不准,留到过后findRest
  2257. createSinglePano(box01)
  2258. }
  2259. return
  2260. }
  2261. console.warn('分数过低,是否有匹配错误?', goodList2[0])
  2262. return tooLows.push(goodList2[0])
  2263. }
  2264. }
  2265. if (goodList2.length) {
  2266. //需要确认两两之间是配对的,也就是都对应同一个box
  2267. let subGroups = [],
  2268. boxes = []
  2269. for (let i = 0, len = goodList2.length; i < len; i++) {
  2270. //向后选择队友
  2271. let match0 = goodList2[i]
  2272. if (subGroups.some(e => e.includes(match0))) continue //被挑选了的没有选择权
  2273. let gr = [match0]
  2274. for (let j = i + 1; j < len; j++) {
  2275. let match1 = goodList2[j]
  2276. if (isSameMatch(match0, match1)) {
  2277. //可能不是同一个,所以需要检验
  2278. gr.push(match1)
  2279. }
  2280. }
  2281. //if(gr.length>1){
  2282. subGroups.push(gr)
  2283. //}
  2284. }
  2285. console.log('lowScores subGroups', subGroups)
  2286. subGroups.forEach(pair => {
  2287. boxes.push(mixMatchBox(pair, lowScores[0].log))
  2288. })
  2289. combineBoxes(boxes) //很可能其实还是同一个,需要检验是否要融合
  2290. }
  2291. })
  2292. //改为之后 findRest, 因为两者都single的可能性低
  2293. /* let judge = box => {
  2294. if (!used(box)) {
  2295. matched.push(box)
  2296. createSinglePano(box)
  2297. }
  2298. }
  2299. tooLows.forEach(e => {
  2300. judge(e.box0)
  2301. judge(e.box1)
  2302. }) */
  2303. }
  2304. }
  2305. function mixMatchBox(list, log) {
  2306. let center = new THREE.Vector3(),
  2307. size = new THREE.Vector3(),
  2308. name,
  2309. bound = new THREE.Box3()
  2310. /* list.forEach(e => {
  2311. center.add(getBoxPos(e))
  2312. size.add(e.size)
  2313. //matched.push(e.box1)
  2314. }) */
  2315. list.forEach(e => {
  2316. let _bound = new THREE.Box3().setFromCenterAndSize(getBoxFinalPos(e), e.size)
  2317. bound.union(_bound)
  2318. })
  2319. /* center.multiplyScalar(1 / list.length)
  2320. size.multiplyScalar(1 / list.length) */
  2321. bound.getCenter(center)
  2322. bound.getSize(size)
  2323. let prefix = log == 'findRest' ? 'rest:' : 'low:'
  2324. let object = {
  2325. name: prefix + list.map(e => e.name),
  2326. boxType: list[0].boxType,
  2327. center,
  2328. size,
  2329. list,
  2330. xProp: list.find(e => e.xProp) && list.find(e => e.xProp).xProp,
  2331. yProp: list.find(e => e.yProp) && list.find(e => e.xProp).yProp,
  2332. }
  2333. let o = restrictSize(size.x, size.z, object)
  2334. size.x = o.x
  2335. size.z = o.y
  2336. let box = new Box(object)
  2337. console.log('mixMatchBox', box)
  2338. return box
  2339. }
  2340. function combineBoxes(boxes) {
  2341. const group = []
  2342. if (boxes.length > 1) {
  2343. const boxType = boxes[0].boxType
  2344. let { min, max } = standards[boxType].widthNormal
  2345. for (let i = 0, len = boxes.length; i < len - 1; i++) {
  2346. let box0 = boxes[i]
  2347. for (let j = i + 1; j < len; j++) {
  2348. let box1 = boxes[j]
  2349. let bound = box0.bound.clone().union(box1.bound)
  2350. let size = bound.getSize(new THREE.Vector3())
  2351. let intersect = box0.bound.intersectsBox(box1.bound)
  2352. let minX = min,
  2353. minZ = min,
  2354. maxX = max,
  2355. maxZ = max
  2356. let xProp = box1.xProp || box0.xProp
  2357. let yProp = box1.yProp || box0.yProp
  2358. if (xProp) {
  2359. if (box0.xProp && box1.xProp && box0.xProp != box1.xProp) continue
  2360. maxX = standards[boxType][xProp].max
  2361. maxZ = standards[boxType][yProp].max
  2362. }
  2363. maxX = Math.max(maxX, box0.size.x, box1.size.x) //必须大于各自的size,否则无法去除本身就oversize的box中包含的
  2364. maxZ = Math.max(maxZ, box0.size.z, box1.size.z)
  2365. let r = intersect ? 1.4 : 1.1 //如果是没有交集,限制更大些
  2366. let maxDiff = 0.3
  2367. if ((size.x < maxX * r || size.x - maxX < maxDiff) && (size.z < maxZ * r || size.z - maxZ < maxDiff)) {
  2368. common.pushToGroupAuto([box0, box1], group)
  2369. }
  2370. }
  2371. }
  2372. if (group.length) {
  2373. //虽然如果三个以上可能会超出maxWidth。 不过3个的概率很低,且可以限制宽度
  2374. group.forEach(pair => {
  2375. let bound = new THREE.Box3()
  2376. pair.forEach(e => {
  2377. bound.union(e.bound)
  2378. e.dispose()
  2379. })
  2380. let size = bound.getSize(new THREE.Vector3())
  2381. let center = bound.getCenter(new THREE.Vector3())
  2382. let info = {
  2383. name: 'mix:' + pair.map(e => e.name + ','),
  2384. mixedFrom: pair,
  2385. boxType,
  2386. center,
  2387. size,
  2388. xProp: pair.find(e => e.xProp) && pair.find(e => e.xProp).xProp,
  2389. yProp: pair.find(e => e.yProp) && pair.find(e => e.xProp).yProp,
  2390. }
  2391. let o = restrictSize(size.x, size.z, info)
  2392. size.x = o.x
  2393. size.z = o.y
  2394. let box = new Box(info)
  2395. console.error('混合', boxType, pair, box)
  2396. })
  2397. }
  2398. }
  2399. }
  2400. function combines(type) {
  2401. //合并boxSolids . battery经常嵌套
  2402. if (type == 'battery') {
  2403. /* let airs = boxes.filter(e => e.boxType == 'air')
  2404. let hangings = boxes.filter(e => e.boxType == 'air-hanging') */
  2405. let batterys = boxesSolid.filter(e => e.boxType == 'battery')
  2406. ;[batterys].forEach(boxes => {
  2407. combineBoxes(boxes)
  2408. })
  2409. }
  2410. }
  2411. let createSinglePano = box => {
  2412. //仅用一个pano中的data来创建
  2413. if (box.score < MinBoxInitialScore) {
  2414. //如Xszq2fv03b的电池pano8-0其实是纸箱、 WZQoMbNmNTu的pano14-0分数0.649
  2415. return console.error('取消createSinglePano: 线框识别分数低,可能错误', box)
  2416. }
  2417. getBoxBase(box)
  2418. let center = getBoxPos(box)
  2419. if (safeBound.distanceToPoint(center) > 0.5) {
  2420. return console.log('取消createSinglePano:超出safebound', box) //可能是错误的线框,如H7pg1tO9oeJ pano8-1
  2421. }
  2422. let info = {
  2423. name: box.sid,
  2424. box0: box,
  2425. center,
  2426. topPos: box.topPos,
  2427. btmPos: box.btmPos,
  2428. }
  2429. preDealBox(info)
  2430. let a = getPoseScore(info.boxposes, true)
  2431. let failed = a < -8
  2432. console.log('createSinglePano', failed ? '失败' : '成功', 'pose score:', a, box)
  2433. if (failed) return
  2434. addLabel(center, 'center', { a: 0.3 })
  2435. info.topPos && addLabel(info.topPos, 'topPos', { a: 0.3 })
  2436. getBoxSize(info)
  2437. new Box(info)
  2438. }
  2439. //去除挨得很近的漫游点,因为两个接近的点match出的值误差很大
  2440. {
  2441. this.removedDatas = {}
  2442. let panoIds = Object.keys(this.datas)
  2443. let len = panoIds.length
  2444. for (let i = 0; i < len; i++) {
  2445. let pano0 = player.model.panos.index[panoIds[i]]
  2446. for (let j = i + 1; j < len; j++) {
  2447. let pano1 = player.model.panos.index[panoIds[j]]
  2448. if (pano0.position.distanceToSquared(pano1.position) < 0.01) {
  2449. //离的很近。保留shape多的那个data
  2450. let remove
  2451. if (this.datas[panoIds[i]].shapes.length > this.datas[panoIds[j]].shapes.length) {
  2452. remove = panoIds[j]
  2453. } else {
  2454. remove = panoIds[i]
  2455. }
  2456. console.log(`删除pano${remove}的data,因pano${panoIds[i]}和pano${panoIds[j]}很近`)
  2457. this.removedDatas[remove] = this.datas[remove]
  2458. delete this.datas[remove]
  2459. }
  2460. }
  2461. }
  2462. }
  2463. this.expandModelBound()
  2464. // if (version == 'vision') this.datasMixed = common.CloneObject(this.datas, null, [player.model.panos.list[0].constructor])
  2465. if (version == 'vision')
  2466. this.datasMixed = common.CloneObject(this.datas, null, undefined, data => {
  2467. return data['category']
  2468. })
  2469. Search('cabinet')
  2470. Search('air')
  2471. Search('battery')
  2472. console.log('----FindRest----')
  2473. waitFindRest.forEach(e => {
  2474. findRest(...e.args)
  2475. combines(e.type)
  2476. })
  2477. }
  2478. /* let getSid = (function(){
  2479. let sid = 0
  2480. return function(){
  2481. return sid++
  2482. }
  2483. })() */
  2484. let done = () => {
  2485. for (let panoId in this.datas) {
  2486. this.datas[panoId].shapes = this.datas[panoId].shapes.map((shape, i) => {
  2487. return Object.assign(
  2488. {
  2489. sid: 'pano' + panoId + '-' + i,
  2490. category: shape.category, //提前 便于调试
  2491. pano: player.model.panos.index[panoId],
  2492. index: i,
  2493. },
  2494. shape
  2495. )
  2496. })
  2497. }
  2498. player.model.chunks.forEach(e => {
  2499. modelBound.union(e.geometry.boundingBox) //注:不用model.boundingBox是 因为union了pano的position的
  2500. })
  2501. //针对部分模型错误,只有底面的,union一下pano.position
  2502. player.model.panos.list.forEach(e => {
  2503. modelBound.expandByPoint(e.position)
  2504. })
  2505. groundY = modelBound.min.y //部分模型底部高度错误,不管了
  2506. groundPlane.setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, groundY, 0))
  2507. /* const w = 0 //这一版的模型bound常常太小,把箱子当墙面,所以扩展一个箱子宽度
  2508. safeBound = player.model.boundingBox.clone().expandByVector(new THREE.Vector3(w, w, w))
  2509. */
  2510. this.ifAnalyze && beginCompute()
  2511. if (version == 'vision') this.load(player.currentPano.id)
  2512. }
  2513. async function load(panoId) {
  2514. let data = await http.post('/service/scene/sceneMarkShape/getInfo', { num: player.$app.config.num, imagePath: panoId + '.jpg' })
  2515. // console.error(data)
  2516. if (!data.data || !data.success) return (this.datas[panoId] = null)
  2517. this.datas[panoId] = data.data
  2518. if (Object.keys(this.datas).length == panosCount && !player.model.panos.list.some(e => e.isAligned() && !(panoId in this.datas))) {
  2519. done()
  2520. }
  2521. }
  2522. async function loadAll() {
  2523. let data = await http.post('/service/scene/sceneMarkShape/getInfos', { num: player.$app.config.num })
  2524. console.error(data)
  2525. if (!data.data || !data.success) return
  2526. data.data.forEach(e => {
  2527. let panoId = e.imagePath.split('.jpg')[0]
  2528. this.datas[panoId] = e
  2529. })
  2530. done()
  2531. }
  2532. let panosCount = 0
  2533. if (!dataList) {
  2534. player.model.panos.list.forEach(e => {
  2535. if (!e.isAligned()) return
  2536. panosCount++
  2537. load.bind(this)(e.id)
  2538. })
  2539. //loadAll.bind(this)() //测试环境
  2540. } else {
  2541. //when version == 'output'
  2542. dataList.forEach(e => {
  2543. let panoId = e.imagePath.split('.jpg')[0]
  2544. this.datas[panoId] = e
  2545. })
  2546. done()
  2547. }
  2548. }
  2549. expandModelBound() {
  2550. const maxDis0 = 1,
  2551. maxDis1 = 3 //不可扩展太宽,否则不准确的框会飘很远,甚至多画多个box,如R7xZsmm9FsG
  2552. let newBound = modelBound.clone()
  2553. let list = []
  2554. for (let panoId in this.datas) {
  2555. this.datas[panoId].shapes.forEach(box => {
  2556. getBoxBase(box)
  2557. if (box.btmPosPredict) {
  2558. let far = box.pano.position.distanceToSquared(box.btmPosPredict)
  2559. if (far > 12) return //太远不准
  2560. let dis = modelBound.distanceToPoint(box.btmPosPredict)
  2561. if (dis > 0 && dis < maxDis1) {
  2562. //maxDis1用来防air-hanging和一些错误的框
  2563. list.push({ box, dis })
  2564. }
  2565. }
  2566. })
  2567. }
  2568. list.sort((a, b) => a.dis - b.dis)
  2569. //let mid = list[Math.floor(list.length/2)]
  2570. let mid = list.length // /2
  2571. for (let i = 0; i < mid; i++) {
  2572. let box = list[i].box
  2573. let pos = box.btmPosPredict
  2574. if (list[i].dis > maxDis0) {
  2575. let p1 = pos.clone().clamp(modelBound.min, modelBound.max)
  2576. let vec = new THREE.Vector3().subVectors(pos, p1).normalize().multiplyScalar(maxDis0)
  2577. pos = new THREE.Vector3().addVectors(p1, vec)
  2578. }
  2579. let marginBound = new THREE.Box3().setFromCenterAndSize(pos, new THREE.Vector3(0.2, 0, 0.2))
  2580. newBound.union(marginBound)
  2581. }
  2582. console.log(newBound)
  2583. skyBoxTight = new BoundingMesh(
  2584. newBound,
  2585. new THREE.MeshBasicMaterial({
  2586. side: THREE.DoubleSide,
  2587. wireframe: true,
  2588. transparent: true,
  2589. opacity: 0.05,
  2590. }),
  2591. 0
  2592. )
  2593. //skyBoxTight.visible = false
  2594. skyBoxTight.updateMatrixWorld() //不update的话raycaster是错的
  2595. meshGroup.add(skyBoxTight)
  2596. this.skyBoxTight = skyBoxTight
  2597. this.safeBound = safeBound = newBound
  2598. boundConfirmed = true
  2599. }
  2600. bindEvents() {
  2601. if (version != 'vision') return
  2602. player.on(PlayerEvents.FlyingStarted, e => {
  2603. //if(e.mode == 'dollhouse')return
  2604. // 点位跳转前清除已有线框
  2605. this.traverse(obj => {
  2606. if (obj.isMesh) {
  2607. obj.geometry.dispose()
  2608. obj.material.dispose()
  2609. }
  2610. })
  2611. this.wireframes.clear()
  2612. this.currentId = null
  2613. })
  2614. player.on(PlayerEvents.FlyingEnded, () => {
  2615. // 点位跳转后加载线框
  2616. if (player.mode != Viewmode.PANORAMA) return // 只有PANORAMA模式下需要加载
  2617. this.load(player.currentPano.id)
  2618. })
  2619. window.boxFrame = this
  2620. if (this.ifAnalyze) {
  2621. setTimeout(() => {
  2622. {
  2623. let btn = document.createElement('button')
  2624. btn.innerHTML = '点击切换box显示'
  2625. btn.onclick = () => {
  2626. this.boxesSolid.forEach(e => ((e.boxHelper.visible = !e.boxHelper.visible), (e.label.visible = !e.label.visible)))
  2627. }
  2628. document.querySelector('#app').appendChild(btn)
  2629. btn.id = 'boxWire'
  2630. btn.style.position = 'fixed'
  2631. btn.style['z-index'] = '100'
  2632. btn.style.background = '#e00472'
  2633. btn.style.padding = '10px'
  2634. btn.style.bottom = '80px'
  2635. }
  2636. {
  2637. let btn = document.createElement('button')
  2638. btn.innerHTML = '点击切换矩形框显示'
  2639. btn.onclick = () => {
  2640. this.wireframes.visible = !this.wireframes.visible
  2641. }
  2642. document.querySelector('#app').appendChild(btn)
  2643. btn.id = 'wireframes'
  2644. btn.style.position = 'fixed'
  2645. btn.style['z-index'] = '100'
  2646. btn.style.background = '#419aff'
  2647. btn.style.padding = '10px'
  2648. btn.style.bottom = '130px'
  2649. }
  2650. }, 1000)
  2651. }
  2652. }
  2653. /**
  2654. * 加载点位标记数据
  2655. * @param {*} panoId
  2656. */
  2657. /* async */ load(panoId) {
  2658. // fetch(texture.getImageURL('images/points/' + panoId + '.json'))
  2659. // .then(data => data.json())
  2660. // .then(data => {
  2661. //let data = await http.post('/service/scene/sceneMarkShape/getInfo', { num: player.$app.config.num, imagePath: panoId + '.jpg' })
  2662. // console.error(data)
  2663. let data = this.datasMixed[panoId]
  2664. if (!data) {
  2665. if (!(panoId in this.datas))
  2666. setTimeout(() => {
  2667. this.load(panoId)
  2668. }, 100) //否则无数据
  2669. return
  2670. } //if (!data.data || !data.success) return
  2671. if (player.currentPano.id != panoId || player.flying || this.currentId == panoId) return // 防止连续跳转点位时,clear后才load好上一点位的数据,导致出现之前的标记
  2672. this.currentId = panoId
  2673. let { shapes, imageHeight, imageWidth } = data //data.data
  2674. let allShapes = shapes.slice()
  2675. shapes.forEach(e => {
  2676. if (e.boxes) allShapes.push(...e.boxes)
  2677. })
  2678. allShapes.forEach(shape => {
  2679. // 填充色和线框色
  2680. // let { fill_color, line_color } = shape
  2681. getUVs(shape)
  2682. getCenterDir(shape, player.currentPano)
  2683. let { fill_color, color = [56, 56, 255] } = shape
  2684. let line_color = [...color, 255]
  2685. if (!fill_color) fill_color = [255, 255, 255, 0]
  2686. if (!line_color) line_color = [255, 0, 0, 255]
  2687. if (shape.boxes) {
  2688. line_color = [20, 205, 255, 255]
  2689. }
  2690. this.showSignalFrom2d(
  2691. shape.category + '-' + shape.sid,
  2692. shape.bbox2,
  2693. imageWidth,
  2694. imageHeight,
  2695. {
  2696. fill: {
  2697. color: new THREE.Color().setRGB(fill_color[0] / 255, fill_color[1] / 255, fill_color[2] / 255),
  2698. opacity: fill_color[3] / 255,
  2699. },
  2700. line: {
  2701. color: new THREE.Color().setRGB(line_color[0] / 255, line_color[1] / 255, line_color[2] / 255),
  2702. opacity: line_color[3] / 255,
  2703. },
  2704. },
  2705. shape.centerDir,
  2706. shape.state == '被删除'
  2707. )
  2708. })
  2709. // })
  2710. // .catch(err => console.log(`点位${panoId}无标记数据或数据出错:`, err))
  2711. }
  2712. /**
  2713. * 根据坐标标记全景图
  2714. *
  2715. * 存在的问题:如果要准确复现全景图上的线框,上下边框会变为弧形。而按顶点连直线的话,180度以上会出bug。
  2716. * 解决方式:目前150度以下只画出4个顶点然后连直线,150度以上准确画出全景图线框。
  2717. */
  2718. showSignalFrom2d(name, rect, w, h, options, centerDir, removed) {
  2719. // 目前rect给的是矩形对角的两个点坐标,将它扩展成四个顶点
  2720. 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])]
  2721. // 2d坐标转3d坐标
  2722. /* let transform2dTo3d = point => {
  2723. // 计算方向向量
  2724. let x = point[0],
  2725. y = point[1]
  2726. let yaw = (-x / w) * (Math.PI * 2)
  2727. let pitch = Math.PI / 2 - (y / h) * Math.PI
  2728. let dir = new THREE.Vector3()
  2729. dir.copy(Vectors.RIGHT).applyAxisAngle(Vectors.BACK, pitch).applyAxisAngle(Vectors.UP, yaw).applyQuaternion(player.currentPano.quaternion)
  2730. return dir
  2731. } */
  2732. // // 计算矩形线框中点坐标(取x、y的平均值)
  2733. // let center = [cornerArr.reduce((a, b) => [a[0] + b[0], 0])[0] / cornerArr.length, cornerArr.reduce((a, b) => [0, a[1] + b[1]])[1] / cornerArr.length]
  2734. // let centerVec = transform2dTo3d(center) // 计算中点3d坐标
  2735. // 根据四个顶点,填充中间点
  2736. let pointArr = []
  2737. for (let i = 0; i < cornerArr.length; i++) {
  2738. let corner1 = cornerArr[i]
  2739. let corner2 = cornerArr[(i + 1) % cornerArr.length]
  2740. pointArr.push(corner1)
  2741. /* // 横向角度超过150度时,3d中边框的弧线已经不太明显,准确画出全景图线框
  2742. if ((rect[2] - rect[0]) / w < 5 / 12 && i % 2 == 0) continue
  2743. const vec = [corner2[0] - corner1[0], corner2[1] - corner1[1]]
  2744. let length = Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
  2745. let num = length / 150
  2746. for (let j = 1; j <= num; j++) {
  2747. pointArr.push([corner1[0] + (vec[0] / num) * j, corner1[1] + (vec[1] / num) * j])
  2748. } */
  2749. }
  2750. //pointArr.push(cornerArr[0], cornerArr[2], cornerArr[1], cornerArr[3]) //对角线
  2751. let points = []
  2752. pointArr.forEach(uv => {
  2753. let dir = getDirByUV(uv, player.currentPano)
  2754. // points.push(dir.sub(centerVec)) // 计算其他点相对于中点的坐标,方便旋转平移等
  2755. points.push(dir)
  2756. })
  2757. // 线框
  2758. const lineGeometry = new THREE.BufferGeometry().setFromPoints(points)
  2759. const lineMaterial = new THREE.LineBasicMaterial({ color: options.line.color, opacity: options.line.opacity, transparent: true, depthTest: false })
  2760. const wireframe = new THREE.LineLoop(lineGeometry, lineMaterial)
  2761. // wireframe.position.copy(centerVec) // 将中点作为线框坐标
  2762. wireframe.renderOrder = 100
  2763. // 填充颜色
  2764. const fillGeometry = lineGeometry.clone().setIndex(new THREE.BufferAttribute(new Uint16Array([0, 1, 3, 2, 3, 1]), 1))
  2765. const fillMaterial = new THREE.MeshBasicMaterial({ color: options.fill.color, opacity: options.fill.opacity, transparent: true, side: THREE.DoubleSide, depthTest: false })
  2766. const plane = new THREE.Mesh(fillGeometry, fillMaterial)
  2767. plane.renderOrder = wireframe.renderOrder - 1
  2768. wireframe.add(plane)
  2769. // 名称
  2770. const textMesh = new TextSprite({
  2771. text: name,
  2772. backgroundColor: { r: options.line.color.r * 255, g: options.line.color.g * 255, b: options.line.color.b * 255, a: 0.8 },
  2773. textColor: { r: 255, g: 255, b: 255, a: 1 },
  2774. borderRadius: 15,
  2775. renderOrder: wireframe.renderOrder + 1,
  2776. player: player,
  2777. })
  2778. textMesh.position.copy(centerDir.clone().add(new THREE.Vector3(0, 0.1, 0)))
  2779. textMesh.lookAt(0, 0, 0) // 看向相机
  2780. textMesh.scale.set(0.12, 0.12, 0.12)
  2781. let group = new THREE.Group()
  2782. group.position.copy(player.currentPano.position)
  2783. group.add(wireframe)
  2784. group.add(textMesh)
  2785. this.wireframes.add(group)
  2786. if (removed) {
  2787. textMesh.sprite.material.opacity = 0.4
  2788. lineMaterial.opacity *= 0.6
  2789. lineMaterial.color.set('#efe')
  2790. }
  2791. }
  2792. }