Exemple #1
0
 def GetProbeMenu(self, probeID, probeIDs=None, *args):
     menu = []
     if probeID == eve.session.shipid:
         return menu
     bp = sm.StartService('michelle').GetBallpark(doWait=True)
     if bp is None:
         return menu
     probeIDs = probeIDs or [probeID]
     if probeID not in probeIDs:
         probeIDs.append(probeID)
     if eve.session.role & (service.ROLE_GML | service.ROLE_WORLDMOD):
         menu.append(('CopyID', self._GMCopyID, (probeID, )))
         menu.append(None)
     if self.IsProbeActive(probeID):
         menu.append(
             (uiutil.MenuLabel('UI/Inflight/Scanner/DeactivateProbe'),
              self.SetProbeActiveStateOff_Check, (probeID, probeIDs)))
     else:
         menu.append(
             (uiutil.MenuLabel('UI/Inflight/Scanner/ActivateProbe'),
              self.SetProbeActiveStateOn_Check, (probeID, probeIDs)))
     probes = self.GetProbeData()
     if probeID in probes:
         probe = probes[probeID]
         scanRanges = self.GetScanRangeStepsByTypeID(probe.typeID)
         menu.append((uiutil.MenuLabel('UI/Inflight/Scanner/ScanRange'),
                      [(util.FmtDist(range), self.SetScanRange_Check,
                        (probeID, probeIDs, range, index + 1))
                       for index, range in enumerate(scanRanges)]))
     menu.append((uiutil.MenuLabel('UI/Inflight/Scanner/RecoverProbe'),
                  self.RecoverProbe_Check, (probeID, probeIDs)))
     menu.append((uiutil.MenuLabel('UI/Inflight/Scanner/DestroyProbe'),
                  self.DestroyProbe_Check, (probeID, probeIDs)))
     return menu
    def GetTypeSubContent(self, nodedata, newitems=0):
        scrolllist = []
        bp = sm.GetService('michelle').GetBallpark()
        for ballID, qty in nodedata.groupItems:
            try:
                dist = bp.DistanceBetween(eve.session.shipid, ballID)
            except:
                dist = 0
                import traceback
                traceback.print_exc()
                sys.exc_clear()

            data = util.KeyVal()
            data.label = cfg.invtypes.Get(
                nodedata.typeID).name + '<t>' + util.FmtAmt(
                    qty) + '<t>' + util.FmtDist(dist)
            data.itemID = ballID
            data.typeID = nodedata.typeID
            data.GetMenu = self.OnGetEntryMenu
            data.OnClick = self.OnEntryClick
            data.showinfo = 1
            data.isTarget = ballID in nodedata.currentTargetIDs
            data.sublevel = 1
            data.Set('sort_' + localization.GetByLabel('UI/Common/Distance'),
                     dist)
            data.Set('sort_' + localization.GetByLabel('UI/Common/Quantity'),
                     qty)
            entry = listentry.Get(None, data=data, decoClass=SurveyScanEntry)
            scrolllist.append(entry)

        return scrolllist
Exemple #3
0
 def GetLabelWithDistance(self):
     label = self.GetLabel()
     bp = sm.GetService('michelle').GetBallpark()
     ball = bp.GetBall(self.invController.itemID)
     if not ball:
         return label
     dist = util.FmtDist(ball.surfaceDist, 1)
     return '%s <color=#66FFFFFF>%s</color>' % (label, dist)
Exemple #4
0
 def GetLabelWithDistance(self):
     label = self.GetLabel()
     if self.clsName in NO_DISTANCE_SHOWN or self.invController.itemID == util.GetActiveShip():
         return label
     if session.solarsystemid:
         ball = sm.GetService('michelle').GetBall(self.invController.itemID)
         if ball:
             dist = util.FmtDist(ball.surfaceDist, 1)
             return '%s <color=#66FFFFFF>%s</color>' % (label, dist)
     return label
 def MoveMouseRangeAction(self, buttonCont, actionButton, length,
                          currentDegree):
     moveMouseResults = actionButton.MoveMouse(length, currentDegree)
     if moveMouseResults:
         currentRange, percOfAllRange = moveMouseResults
         self.MoveMouseRangeCallback(usingRangeOption=True,
                                     currentRange=currentRange,
                                     percOfAllRange=percOfAllRange)
         self.SetOptionRangeText(util.FmtDist(currentRange))
         self.SetRangeCircle(buttonCont.degree, percOfAllRange)
         self.SelectButton(buttonCont)
     return moveMouseResults
Exemple #6
0
 def UpdateRubberLinkLabels(self, surfacePointA, surfacePointB):
     self.rubberLinkLabelContainer.left = uicore.uilib.x + 3
     self.rubberLinkLabelContainer.top = uicore.uilib.y + 3
     if surfacePointA == surfacePointB:
         length = 0.0
     else:
         length = surfacePointA.GetDistanceToOther(surfacePointB) * self.planetUISvc.planet.radius
     self.rubberLinkLabels.distance.text = util.FmtDist(length)
     powerUsage = planetCommon.GetPowerUsageForLink(const.typeTestPlanetaryLink, length, 0, self.linkParams)
     cpuUsage = planetCommon.GetCpuUsageForLink(const.typeTestPlanetaryLink, length, 0, self.linkParams)
     self.rubberLinkLabels.power.text = localization.GetByLabel('UI/PI/Common/MegaWattsAmount', amount=powerUsage)
     self.rubberLinkLabels.cpu.text = localization.GetByLabel('UI/PI/Common/TeraFlopsAmount', amount=cpuUsage)
Exemple #7
0
 def IndicateWarp(self):
     """
         returns the header text and subtext to display above HUD when ship is warping.
         Can return None, None which means there is nothing to display
     """
     destinationItemID, destinationBookmarkID, destinationfleetMemberID, destinationPosition, actualDestinationPosition = self.warpDestinationCache
     if not destinationPosition:
         self.LogError(
             'Space::IndicateWarp: Something is messed up, didnt get ballpark coordinates to verify warp'
         )
         return (None, None)
     ballPark = sm.GetService('michelle').GetBallpark()
     if not ballPark:
         self.LogWarn(
             'Space::IndicateWarp: Trying to indicate warp without a ballpark?'
         )
         return (None, None)
     centeredDestText = '<center>' + getattr(self, 'warpDestText', '')
     text = centeredDestText
     egoball = ballPark.GetBall(ballPark.ego)
     if actualDestinationPosition is not None:
         warpDirection = [
             actualDestinationPosition[0] - egoball.x,
             actualDestinationPosition[1] - egoball.y,
             actualDestinationPosition[2] - egoball.z
         ]
     else:
         warpDirection = [
             destinationPosition[0] - egoball.x,
             destinationPosition[1] - egoball.y,
             destinationPosition[2] - egoball.z
         ]
     dist = self.VectorLength(warpDirection)
     if dist:
         distanceText = '<center>' + localization.GetByLabel(
             'UI/Inflight/ActiveItem/SelectedItemDistance',
             distToItem=util.FmtDist(dist))
         if actualDestinationPosition is None:
             text = localization.GetByLabel(
                 'UI/Inflight/Messages/WarpIndicatorWithDistanceAndBubble',
                 warpDestination=centeredDestText,
                 distance=distanceText)
         else:
             text = localization.GetByLabel(
                 'UI/Inflight/Messages/WarpIndicatorWithDistance',
                 warpDestination=centeredDestText,
                 distance=distanceText)
     self.LogInfo('Space::IndicateWarp', text)
     return (
         localization.GetByLabel('UI/Inflight/Messages/WarpDriveActive'),
         text)
Exemple #8
0
def _GetRangeMenu(itemID, dist, currentDistance, rangesList, mainFunc,
                  setDefaultFunc, atCurrentRangeLabel, setDefaultLabel, *args):
    rangeMenu = []
    rangeSubMenu = []
    for eachRange in rangesList:
        fmtRange = util.FmtDist(eachRange)
        rangeSubMenu.append((fmtRange, setDefaultFunc, (eachRange, )))
        rangeMenu.append((fmtRange, mainFunc, (itemID, eachRange)))

    rangeMenu += [(uiutil.MenuLabel(atCurrentRangeLabel,
                                    {'currentDistance': currentDistance}),
                   mainFunc, (itemID, dist)), None,
                  (uiutil.MenuLabel(setDefaultLabel), rangeSubMenu)]
    return rangeMenu
Exemple #9
0
 def UpdateDistance(self):
     sourceID = self.sr.Get('sourceID', None)
     targetID = self.sr.Get('targetID', None)
     if not sourceID and not targetID:
         return
     sourceBall = sm.GetService('michelle').GetBall(sourceID)
     if not sourceBall:
         return
     targetBall = sm.GetService('michelle').GetBall(targetID)
     if not targetBall:
         return
     bp = sm.GetService('michelle').GetBallpark()
     dist = bp.DistanceBetween(sourceID, targetID)
     self.sr.distancelabel.text = util.FmtDist(dist)
     self.sr.distancelabel.left = self.width / 2 - self.sr.distancelabel.textwidth / 2
 def UpdateData(self):
     ball = self.ball()
     if not ball:
         return
     dist = ball.surfaceDist
     distanceInMeters = int(dist)
     dataUsedForLabel = (self.label, int(distanceInMeters))
     if dataUsedForLabel != self.lastDataUsedForLabel:
         newText = localization.GetByLabel('UI/Inflight/Target/DataLabel',
                                           label=self.label,
                                           distance=util.FmtDist(dist))
         self.sr.label.text = newText
         self.lastDataUsedForLabel = dataUsedForLabel
     if self.updatedamage:
         self.UpdateDamage()
Exemple #11
0
 def ValidateAddExtractorHead(self, pinID, headID, latitude, longitude):
     if self.colonyData is None:
         raise RuntimeError(
             'Unable to validate new extractor head - no colony data')
     if latitude < 0 or latitude > math.pi:
         raise RuntimeError(
             'Invalid value for latitude - must be between 0..pi')
     if longitude < 0 or longitude > 2 * math.pi:
         raise RuntimeError(
             'Invalid value for longitude - must be between 0..2pi')
     self.PreValidateAddExtractorHead(pinID, latitude, longitude)
     pin = self.GetPin(pinID)
     if not pin:
         raise UserError('PinDoesNotExist')
     if not pin.IsExtractor():
         raise UserError('PinDoesNotHaveHeads')
     if pin.FindHead(headID) is not None:
         raise UserError('CannotAddHeadAlreadyExists')
     if len(pin.heads) >= ECU_MAX_HEADS:
         raise UserError('CannotPlaceHeadLimitReached')
     cpuDelta = pin.GetCpuUsage(numHeads=len(pin.heads) +
                                1) - pin.GetCpuUsage()
     powerDelta = pin.GetPowerUsage(numHeads=len(pin.heads) +
                                    1) - pin.GetPowerUsage()
     if cpuDelta + self.colonyData.GetColonyCpuUsage(
     ) > self.colonyData.GetColonyCpuSupply():
         raise UserError(
             'CannotAddToColonyCPUUsageExceeded',
             {'typeName': (const.UE_LOC, 'UI/PI/Common/ExtractorHead')})
     if powerDelta + self.colonyData.GetColonyPowerUsage(
     ) > self.colonyData.GetColonyPowerSupply():
         raise UserError(
             'CannotAddToColonyPowerUsageExceeded',
             {'typeName': (const.UE_LOC, 'UI/PI/Common/ExtractorHead')})
     spA = SurfacePoint(radius=self.GetPlanetRadius(),
                        theta=pin.longitude,
                        phi=pin.latitude)
     spB = SurfacePoint(radius=self.GetPlanetRadius(),
                        theta=longitude,
                        phi=latitude)
     angleBetween = spA.GetAngleBetween(spB)
     areaOfInfluence = pin.GetAreaOfInfluence()
     if angleBetween > areaOfInfluence:
         raise UserError('CannotPlaceHeadTooFarAway', {
             'maxDist':
             util.FmtDist(areaOfInfluence * self.planet.radius)
         })
     self.PostValidateAddExtractorHead(pinID, latitude, longitude)
    def GetHeaderAndSubtextForActionIndication(self, ballMode, followId, followRange, ball = None, *args):
        """
            returns the header text and subtext for the ship's actions.
            Can return None, None which means there is nothing to display
        """
        headerText = None
        subText = None
        if ballMode != destiny.DSTBALL_GOTO and ball is not None:
            sm.GetService('menu').ClearAlignTargets()
        if followId != 0 and ballMode in (destiny.DSTBALL_ORBIT, destiny.DSTBALL_FOLLOW):
            name = sm.GetService('space').GetWarpDestinationName(followId)
            myRange = followRange
            rangeText = util.FmtDist(myRange, maxdemicals=0)
            if ballMode == destiny.DSTBALL_ORBIT:
                headerText = localization.GetByLabel('UI/Inflight/Messages/OrbitingHeader')
                subText = localization.GetByLabel('UI/Inflight/Messages/OrbitingSubText', targetName=name, rangeText=rangeText)
            elif ballMode == destiny.DSTBALL_FOLLOW:
                if myRange in (const.approachRange, 0):
                    headerText = localization.GetByLabel('UI/Inflight/Messages/ApproachingHeader')
                    subText = localization.GetByLabel('UI/Inflight/Messages/ApproachingSubText', targetName=name)
                else:
                    headerText = localization.GetByLabel('UI/Inflight/Messages/KeepingAtRangeHeader')
                    subText = localization.GetByLabel('UI/Inflight/Messages/KeepingAtRangeSubText', targetName=name, rangeText=rangeText)
        elif ballMode == destiny.DSTBALL_GOTO:
            alignTargetID, aligningToBookmark = sm.GetService('menu').GetLastAlignTarget()
            if not alignTargetID and not aligningToBookmark:
                return (None, None)
            headerText = localization.GetByLabel('UI/Inflight/Messages/AligningHeader')
            if alignTargetID:
                if util.IsCharacter(alignTargetID):
                    subText = localization.GetByLabel('UI/Inflight/Messages/AligningToPlayerSubText', charID=alignTargetID)
                else:
                    try:
                        name = sm.GetService('space').GetWarpDestinationName(alignTargetID)
                        subText = localization.GetByLabel('UI/Inflight/Messages/AligningToLocationSubText', targetName=name)
                    except:
                        subText = localization.GetByLabel('UI/Inflight/Messages/AligningUnknownSubText')

            elif aligningToBookmark:
                subText = localization.GetByLabel('UI/Inflight/Messages/AligningToBookmarkSubText')
            else:
                subText = localization.GetByLabel('UI/Inflight/Messages/AligningUnknownSubText')
        elif ballMode == destiny.DSTBALL_WARP:
            return self.IndicateWarp()
        return (headerText, subText)
 def UpdateDisplayName(self):
     displayName = ''
     if self.itemID == session.shipid and self.slimItem:
         shipCategory = cfg.invgroups.Get(self.slimItem.groupID).name
         displayName = '<b>' + localization.GetByLabel(
             'UI/Inflight/ActionButtonsYourShipWithCategory',
             categoryOfYourShip=shipCategory)
     elif self.manyItemsData and self.fallBackDisplayName:
         displayName = self.fallBackDisplayName
     elif self.slimItem:
         displayName = '<b>%s</b>' % uix.GetSlimItemName(self.slimItem)
         bp = sm.StartService('michelle').GetBallpark()
         if bp:
             ball = bp.GetBall(self.itemID)
             if ball:
                 displayName += ' ' + util.FmtDist(ball.surfaceDist)
     elif self.bookmarkInfo:
         displayName = self.bookmarkInfo.memo
     elif self.fallBackDisplayName:
         displayName = self.fallBackDisplayName
     self.SetDisplayName(displayName)
 def UpdateData(self):
     ball = self.ball()
     if not ball:
         return
     dist = ball.surfaceDist
     distanceInMeters = int(dist)
     if self.label != self.lastTextUsedForLabel:
         self.SetNameLabels(fullLabel=self.label)
         self.lastTextUsedForLabel = self.label
     if distanceInMeters != self.lastTextUsedDistance:
         self.sr.distanceLabel.text = '<center>' + util.FmtDist(dist)
         self.FadeText(self.sr.label2)
         self.lastTextUsedDistance = distanceInMeters
     if self.shipLabel != self.lastTextUsedForShipType:
         if self.shipLabel:
             self.sr.shipLabel.display = True
             self.sr.shipLabel.text = '<center>' + self.shipLabel
             self.FadeText(self.sr.shipLabel)
             self.lastTextUsedForShipType = self.shipLabel
         else:
             self.sr.shipLabel.text = ''
             self.sr.shipLabel.display = False
 def ValidateMoveExtractorHead(self, pinID, headID, latitude, longitude):
     if self.colonyData is None:
         raise RuntimeError('Unable to validate extractor head movement - no colony data')
     if latitude < 0 or latitude > math.pi:
         raise RuntimeError('Invalid value for latitude - must be between 0..pi')
     if longitude < 0 or longitude > 2 * math.pi:
         raise RuntimeError('Invalid value for longitude - must be between 0..2pi')
     self.PreValidateMoveExtractorHead(pinID, headID, latitude, longitude)
     pin = self.GetPin(pinID)
     if not pin:
         raise UserError('PinDoesNotExist')
     if not pin.IsExtractor():
         raise UserError('PinDoesNotHaveHeads')
     if pin.FindHead(headID) is None:
         raise UserError('CannotMoveHeadNotPresent')
     spA = SurfacePoint(theta=pin.longitude, phi=pin.latitude)
     spB = SurfacePoint(theta=longitude, phi=latitude)
     angleBetween = spA.GetAngleBetween(spB)
     areaOfInfluence = pin.GetAreaOfInfluence()
     if angleBetween > areaOfInfluence:
         raise UserError('CannotPlaceHeadTooFarAway', {'maxDist': util.FmtDist(angleBetween * self.planet.radius)})
     self.PostValidateMoveExtractorHead(pinID, headID, latitude, longitude)
 def LoadTooltipPanel(self, tooltipPanel, *args):
     tooltipPanel.LoadGeneric2ColumnTemplate()
     shortcutString = None
     reasonString = None
     distString = None
     keywords = {}
     if isinstance(self.action[1], basestring):
         reasonString = self.action[1]
         if self.actionID == 'UI/Inflight/WarpToWithinDistance':
             keywords['distance'] = sm.GetService(
                 'menu').GetDefaultActionDistance('WarpTo')
     else:
         if isinstance(self.action[0], uiutil.MenuLabel):
             actionNamePath, keywords = self.action[0]
         if self.actionID in ('UI/Inflight/OrbitObject',
                              'UI/Inflight/Submenus/KeepAtRange'):
             key = GetGlobalActiveItemKeyName(actionNamePath)
             current = sm.GetService('menu').GetDefaultActionDistance(key)
             if current is not None:
                 distString = util.FmtDist(current)
             else:
                 distString = localization.GetByLabel(
                     'UI/Menusvc/MenuHints/NoDistanceSet')
     if hasattr(self, 'cmdName'):
         shortcutString = uicore.cmd.GetShortcutStringByFuncName(
             self.cmdName)
     actionName = localization.GetByLabel(self.actionID, **keywords)
     if distString:
         hint = localization.GetByLabel(
             'UI/Menusvc/MenuHints/SelectedItemActionWithDist',
             actionName=actionName,
             distanceString=distString)
     else:
         hint = actionName
     tooltipPanel.AddLabelShortcut(hint, shortcutString)
     if reasonString:
         tooltipPanel.AddLabelMedium(text=reasonString,
                                     colSpan=tooltipPanel.columns)
Exemple #17
0
    def Search(self, group=None, *args):
        ignoredGroups = [
            const.groupPlanet, const.groupMoon, const.groupAsteroidBelt,
            const.groupSun, const.groupSecondarySun, const.groupStargate,
            const.groupCapturePointTower, const.groupControlBunker,
            const.groupSentryGun, const.groupBillboard,
            const.groupDestructibleStationServices
        ]
        wnd = DestroyableItemsWindow.GetIfOpen()
        bp = sm.GetService('michelle').GetBallpark()
        targets = []
        self.ballParkData = []
        playersPresent = []
        if util.IsSolarSystem(session.locationid):
            for ballID in bp.balls.keys():
                try:
                    item = bp.GetInvItem(ballID)
                    if item and item.groupID not in ignoredGroups:
                        self.ballParkData.append(item)
                        if item.categoryID == const.categoryShip and bp.GetBall(
                                ballID).isInteractive:
                            playersPresent.append(item.charID)
                except:
                    sys.exc_clear()
                    continue

            if group == 'all':
                groups = [
                    const.categoryDrone, const.categoryCelestial,
                    const.categoryShip, const.categoryStructure,
                    const.categoryDeployable, const.categoryEntity,
                    const.categorySovereigntyStructure
                ]
                targets += self.Collate(self.ballParkData,
                                        group=groups,
                                        players=playersPresent)
            else:
                targets += self.Collate(self.ballParkData,
                                        group=group,
                                        players=playersPresent)
        nodes = []
        verbose = settings.char.ui.Get('verboseDestroyables', 0)
        maxRange = self.dir_rangeinput.GetValue() * 1000
        if targets:
            for each in targets:
                ownertype = each[1]
                ownername = each[4]
                distance = each[5]
                if maxRange and maxRange < distance:
                    continue
                itemname = cfg.invtypes.Get(each[2]).name
                displayname = cfg.evelocations.Get(each[3]).name
                if not displayname:
                    displayname = '-'
                if verbose:
                    x = each[7]
                    y = each[8]
                    z = each[9]
                    label = u'%s<t>%s<t>%s<t>%s<t>%s<t>%s<t>%s<t>%s<t>%s<t>%s<t>%s' % (
                        each[0], each[6], each[3],
                        util.FmtDist(distance, maxdemicals=1), itemname,
                        displayname, ownername, ownertype, x, y, z)
                    hint = u'Name: %s<br>Type: %s<br>Owner: %s<br>State: %s<br>Relative Position: [%s, %s, %s]' % (
                        displayname, itemname, ownername, each[6], x, y, z)
                    entry = listentry.Get(
                        'InsiderDestroyables', {
                            'label': label,
                            'hint': hint,
                            'entrytype': each[0],
                            'ownertype': ownertype,
                            'itemname': itemname,
                            'typeID': each[2],
                            'itemID': each[3],
                            'ownername': ownername,
                            'name': displayname,
                            u'Distance': util.FmtDist(distance, maxdemicals=1),
                            u'sort_Distance': distance,
                            'x': x,
                            'y': y,
                            'z': z
                        })
                else:
                    label = u'%s<t>%s<t>%s' % (each[0], each[3], itemname)
                    hint = u'Name: %s<br>Type: %s<br>Owner: %s<br>State: %s' % (
                        displayname, itemname, ownername, each[6])
                    entry = listentry.Get(
                        'InsiderDestroyables', {
                            'label': label,
                            'hint': hint,
                            'entrytype': each[0],
                            'ownertype': ownertype,
                            'itemname': itemname,
                            'typeID': each[2],
                            'itemID': each[3],
                            'ownername': ownername,
                            'name': displayname
                        })
                nodes.append(entry)

        if verbose:
            self.scroll.Load(contentList=nodes,
                             headers=[
                                 'Entry Type', 'State', 'Item ID', 'Distance',
                                 'Type', 'Name', 'Owner Name', 'Owner Type',
                                 'x (m)', 'y (m)', 'z (m)'
                             ],
                             fixedEntryHeight=18)
        else:
            self.scroll.Load(contentList=nodes,
                             headers=['Entry Type', 'Item ID', 'Type'],
                             fixedEntryHeight=18)
        if not nodes:
            self.scroll.ShowHint(u'No items found')
        else:
            self.scroll.ShowHint()
Exemple #18
0
    def PreviewType(self, typeID, subsystems=None):
        if getattr(self, 'running', False):
            return
        self.running = True
        self.previewingWhat = 'type'
        if getattr(self, 'btnGroup', None):
            self.btnGroup.display = False
        self.SetCaption(localization.GetByLabel('UI/Preview/PreviewCaption'))
        self.sr.title.display = True
        self.sr.subtitle.display = True
        typeID = int(typeID)
        if typeID != self.typeID:
            self.CloseSubSystemWnd()
        isFirst = self.typeID is None
        typeOb = cfg.invtypes.Get(typeID)
        groupID = typeOb.groupID
        groupOb = cfg.invgroups.Get(groupID)
        categoryID = groupOb.categoryID
        self.categoryID = categoryID
        self.groupID = groupID
        self.typeID = typeID
        self.sr.title.text = cfg.invtypes.Get(typeID).name
        rad = 4.0
        self.textCont.display = False
        self.SetMinSize([420, 320])
        self.SetMaxSize([None, None])
        self.sr.subtitle.text = ''
        godma = sm.GetService('godma')
        try:
            techLevel = godma.GetTypeAttribute(typeID,
                                               const.attributeTechLevel)
        except:
            techLevel = 1.0

        self.loadingWheel.Show()
        if categoryID == const.categoryShip and techLevel == 3.0:
            self.sr.sceneContainer.PrepareSpaceScene()
            if subsystems is None:
                subsystems = {}
                subSystemsForType = {}
                for group in cfg.groupsByCategories.get(
                        const.categorySubSystem, []):
                    if group.groupID not in subSystemsForType:
                        subSystemsForType[group.groupID] = []
                    for t in cfg.typesByGroups.get(group.groupID, []):
                        if t.published and godma.GetTypeAttribute(
                                t.typeID,
                                const.attributeFitsToShipType) == typeID:
                            subSystemsForType[group.groupID].append(t.typeID)

                for k, v in subSystemsForType.iteritems():
                    subsystems[k] = random.choice(v)

            model = sm.StartService('t3ShipSvc').GetTech3ShipFromDict(
                typeID, subsystems)
            radius = round(model.GetBoundingSphereRadius() * 2, 0)
            self.SetShipSubLabel(typeOb, groupOb, radius)
            kv = util.KeyVal(typeID=typeID)
            form.AssembleShip.Open(windowID='PreviewSubSystems',
                                   ship=kv,
                                   groupIDs=None,
                                   isPreview=True,
                                   setselected=subsystems)
        elif self.categoryID in paperDollCategories:
            desc = typeOb.description
            desc = desc or ''
            for each in ('<b>', '</b>', '\r'):
                desc = desc.replace(each, '')

            desc = desc.replace('\n', '<br>')
            self.desc.SetValue(desc)
            self.textCont.display = True
            self.SetMinSize([320, 470])
            self.SetMaxSize([800, 950])
            self.sr.sceneContainer.cameraParent.value = trinity.TriVector(
                9.0, -1000, 0.0)
            self.sr.sceneContainer.PrepareInteriorScene()
            scene = self.sr.sceneContainer.scene
            factory = pd.Factory()
            asset = GetPaperDollResource(typeID)
            if asset is None:
                log.LogError('PreviewWnd::PreviewType - Invalid asset')
                self.loadingWheel.Hide()
                return
            path = asset.resPath
            genderID = asset.resGender
            self.mannequin = pd.PaperDollCharacter(factory)
            self.mannequin.doll = pd.Doll(
                'mannequin', gender=ccUtil.GenderIDToPaperDollGender(genderID))
            if genderID == ccConst.GENDERID_MALE:
                self.mannequin.doll.Load(
                    'res:/Graphics/Character/DNAFiles/Mannequin/MaleMannequin.prs',
                    factory)
            else:
                self.mannequin.doll.Load(
                    'res:/Graphics/Character/DNAFiles/Mannequin/FemaleMannequin.prs',
                    factory)
            while self.mannequin.doll.busyUpdating:
                blue.synchro.Yield()
                if self.mannequin is None:
                    return

            textureQuality = settings.public.device.Get(
                'charTextureQuality',
                sm.GetService('device').GetDefaultCharTextureQuality())
            resolution = ccConst.TEXTURE_RESOLUTIONS[textureQuality]
            self.mannequin.doll.overrideLod = 0
            self.mannequin.doll.textureResolution = resolution
            self.mannequin.Spawn(scene, usePrepass=False)
            while self.mannequin.doll.busyUpdating:
                blue.synchro.Yield()
                if self.mannequin is None:
                    return

            meshListPre = self.mannequin.doll.buildDataManager.GetMeshes(
                includeClothMeshes=True)
            self.mannequin.doll.SetItemType(factory, path, weight=1.0)
            self.mannequin.Update()
            while self.mannequin.doll.busyUpdating:
                blue.synchro.Yield()
                if self.mannequin is None:
                    return

            meshListPost = self.mannequin.doll.buildDataManager.GetMeshes(
                includeClothMeshes=True)
            animationUpdater = GameWorld.GWAnimation(
                'res:/Animation/MorphemeIncarna/Export/Mannequin/Mannequin.mor'
            )
            if animationUpdater is not None:
                self.mannequin.avatar.animationUpdater = animationUpdater
                if self.mannequin.doll.gender == pd.GENDER.FEMALE:
                    animationUpdater.network.SetAnimationSetIndex(0)
                else:
                    animationUpdater.network.SetAnimationSetIndex(1)
            bBox = (geo2.Vector(1000.0, 1000.0,
                                1000.0), geo2.Vector(-1000.0, -1000.0,
                                                     -1000.0))
            if groupID in MESH_NAMES_BY_GROUPID:
                meshName = MESH_NAMES_BY_GROUPID[groupID]
                found = False
                for mesh in meshListPost:
                    if mesh.name.startswith(
                            meshName) or mesh not in meshListPre:
                        fromMesh = mesh.geometry.GetBoundingBox(0)
                        bBox[0].x = min(bBox[0].x, fromMesh[0].x)
                        bBox[0].y = min(bBox[0].y, fromMesh[0].y)
                        bBox[0].z = min(bBox[0].z, fromMesh[0].z)
                        bBox[1].x = max(bBox[1].x, fromMesh[1].x)
                        bBox[1].y = max(bBox[1].y, fromMesh[1].y)
                        bBox[1].z = max(bBox[1].z, fromMesh[1].z)
                        found = True

                if not found:
                    bBox = (geo2.Vector(-0.1, 1.6,
                                        -0.1), geo2.Vector(0.1, 1.8, 0.1))
            center = ((bBox[1].x + bBox[0].x) / 2.0,
                      (bBox[1].y + bBox[0].y) / 2.0,
                      (bBox[1].z + bBox[0].z) / 2.0)
            rad = geo2.Vec3Length(bBox[0] - bBox[1])
            rad = max(rad, 0.3)
            self.sr.sceneContainer.cameraParent.value = trinity.TriVector(
                *center)
            floor = trinity.Load(ccConst.CUSTOMIZATION_FLOOR)
            scene.dynamics.append(floor)
            model = None
        elif self.groupID in const.turretModuleGroups:
            self.sr.sceneContainer.PrepareSpaceScene(
                0.0, 'res:/dx9/scene/fitting/previewTurrets.red')
            model = trinity.Load(
                'res:/dx9/model/ship/IconPreview/PreviewTurretShip.red')
            tSet = turretSet.TurretSet.FitTurret(model,
                                                 None,
                                                 typeID,
                                                 1,
                                                 checkSettings=False)
            if tSet is not None:
                boundingSphere = tSet.turretSets[0].boundingSphere
                model.boundingSphereRadius = boundingSphere[3]
                model.boundingSphereCenter = boundingSphere[:3]
                if model.boundingSphereCenter[1] < 2.0:
                    model.boundingSphereCenter = (boundingSphere[0], 2.0,
                                                  boundingSphere[2])
                for ts in tSet.turretSets:
                    ts.bottomClipHeight = 0.0
                    ts.FreezeHighDetailLOD()
                    ts.ForceStateDeactive()
                    ts.EnterStateIdle()

                self.sr.subtitle.text = localization.GetByLabel(
                    'UI/Preview/ShipSubLabelNoRace',
                    groupName=groupOb.groupName,
                    length=util.FmtDist(model.boundingSphereRadius))
        elif self.groupID in const.turretAmmoGroups:
            self.sr.sceneContainer.PrepareSpaceScene(
                0.0, 'res:/dx9/scene/fitting/previewAmmo.red')
            model = trinity.Load(
                'res:/dx9/model/ship/IconPreview/PreviewAmmoShip.red')
            self.sr.sceneContainer.AddToScene(model)
            ammoRedFile = typeOb.GraphicFile()
            ammoRedFile = ammoRedFile[:-4] + '_hi' + ammoRedFile[-4:]
            ammo = trinity.Load(ammoRedFile)
            if ammo.__bluetype__ == 'trinity.EveMissile':
                floatHeight = ammo.boundingSphereRadius - ammo.boundingSphereCenter[
                    2]
                floatHeight += 0.2 * ammo.boundingSphereRadius
                model.boundingSphereRadius = ammo.boundingSphereRadius + floatHeight
                model.boundingSphereCenter = (0.0, ammo.boundingSphereRadius +
                                              0.5 * floatHeight, 0.0)
                warhead = ammo.warheads[0]
                warhead.rotation = geo2.QuaternionRotationAxis((1.0, 0.0, 0.0),
                                                               -0.5 * math.pi)
                warhead.translation = (0.0, floatHeight, 0.0)
                warhead.startDataValid = True
                del warhead.children[:]
                model.children.append(warhead)
                warheadReflection = warhead.CopyTo()
                warheadReflection.rotation = geo2.QuaternionRotationAxis(
                    (1.0, 0.0, 0.0), 0.5 * math.pi)
                warheadReflection.translation = (0.0, -floatHeight, 0.0)
                warheadReflection.startDataValid = True
                model.children.append(warheadReflection)
                self.sr.subtitle.text = localization.GetByLabel(
                    'UI/Preview/ShipSubLabelNoRace',
                    groupName=groupOb.groupName,
                    length=util.FmtDist(model.boundingSphereRadius))
            else:
                log.LogWarn(
                    'type', typeID,
                    ' is not an EveMissile but still wants to be previewed as one'
                )
                model = None
        else:
            self.sr.sceneContainer.PrepareSpaceScene()
            fileName = typeOb.GraphicFile()
            if fileName == '':
                log.LogWarn('type', typeID, 'has no graphicFile')
                self.loadingWheel.Hide()
                return
            fileName = fileName.replace(':/Model', ':/dx9/Model').replace(
                '.blue', '.red')
            fileName = fileName.partition(' ')[0]
            model = trinity.Load(fileName)
            radius = round(model.GetBoundingSphereRadius() * 2, 0)
            self.SetShipSubLabel(typeOb, groupOb, radius)
            if model is None:
                self.sr.sceneContainer.ClearScene()
                self.loadingWheel.Hide()
                raise UserError('PreviewNoModel')
            if getattr(model, 'boosters', None) is not None:
                model.boosters = None
            if getattr(model, 'modelRotationCurve', None) is not None:
                model.modelRotationCurve = None
            if getattr(model, 'modelTranslationCurve', None) is not None:
                model.modelTranslationCurve = None
        if hasattr(model, 'ChainAnimationEx'):
            model.ChainAnimationEx('NormalLoop', 0, 0, 1.0)
        self.sr.sceneContainer.AddToScene(model)
        camera = self.sr.sceneContainer.camera
        navigation = self.sr.navigation
        spaceObject = False
        if hasattr(model, 'GetBoundingSphereRadius'):
            rad = model.GetBoundingSphereRadius()
            spaceObject = True
        minZoom = rad + self.sr.sceneContainer.frontClip
        alpha = self.sr.sceneContainer.fieldOfView / 2.0
        if spaceObject:
            maxZoom = max(rad * (1 / math.tan(alpha)) * 2, 1.0)
            camera.translationFromParent = minZoom * 2
        else:
            maxZoom = min(rad * (1 / math.tan(alpha * 1.5)), 7.0)
            camera.translationFromParent = minZoom * 3
        navigation.SetMinMaxZoom(minZoom, maxZoom)
        self.sr.sceneContainer.UpdateViewPort()
        self.BringToFront()
        if isFirst:
            uthread.new(self.OrbitParent)
        self.loadingWheel.Hide()
        self.running = False
def DefaultWarpToLabel():
    defaultWarpDist = sm.GetService('menu').GetDefaultActionDistance('WarpTo')
    label = uiutil.MenuLabel('UI/Inflight/WarpToWithinDistance', {'distance': util.FmtDist(float(defaultWarpDist))})
    return label
 def _GetDistance(self, value, languageID, *args, **kwargs):
     return util.FmtDist(value, maxdemicals=kwargs.get('decimalPlaces', 3))
Exemple #21
0
    def UpdateAll(self, updateActions=0):
        if not self or self.destroyed:
            return
        if eve.session.shipid in self.itemIDs:
            self.itemIDs.remove(eve.session.shipid)
        bp = sm.GetService('michelle').GetBallpark()
        if not self.ImVisible() or not bp or not self.itemIDs:
            self.sr.updateTimer = None
            self.FlushContent()
            return
        goForSlim = 1
        slimItems = []
        invItems = []
        fleetMember = None
        for itemID in self.itemIDs:
            blue.pyos.BeNice()
            if sm.GetService('fleet').IsMember(itemID):
                fleetMember = cfg.eveowners.Get(itemID)
                break
            slimItem = None
            if goForSlim:
                slimItem = uix.GetBallparkRecord(itemID)
                if slimItem:
                    slimItems.append(slimItem)
            if not slimItem:
                invItem = self.TryGetInvItem(itemID)
                if invItem:
                    invItems.append(invItem)
                    goForSlim = 0

        if not slimItems and not invItems and not fleetMember:
            self.itemIDs = []
            self.lastActionSerial = None
            self.lastActionDist = None
            self.FlushContent()
            return
        if not self or self.destroyed:
            return
        text = ''
        blue.pyos.BeNice()
        updateActions = updateActions or 0
        typeID = None
        fleetSlim = None
        if fleetMember:
            multi = 1
            text = fleetMember.name
            typeID = fleetMember.typeID
            fleetSlim = self.GetSlimItemForCharID(fleetMember.id)
            blue.pyos.BeNice()
        elif invItems:
            text = uix.GetItemName(invItems[0])
            typeID = invItems[0].typeID
            multi = len(invItems)
            blue.pyos.BeNice()
        elif slimItems:
            text = uix.GetSlimItemName(slimItems[0])
            typeID = slimItems[0].typeID
            multi = len(slimItems)
            if multi == 1:
                slimItem = slimItems[0]
                itemID = slimItem.itemID
                ball = bp.GetBall(itemID)
                if not ball:
                    self.itemIDs = []
                    self.sr.updateTimer = None
                    self.FlushContent()
                    return
                dist = ball.surfaceDist
                if dist is not None:
                    md = None
                    myball = bp.GetBall(eve.session.shipid)
                    if myball:
                        md = myball.mode
                    text += '<br>' + localization.GetByLabel(
                        'UI/Inflight/ActiveItem/SelectedItemDistance',
                        distToItem=util.FmtDist(dist, maxdemicals=1))
                    if not self.lastActionDist or md != self.lastActionDist[
                            1] or self.CheckDistanceUpdate(
                                self.lastActionDist[0], dist):
                        self.lastActionDist = (dist, md)
                        updateActions = 1
                sec = slimItem.securityStatus
                if sec:
                    text += '<br>' + localization.GetByLabel(
                        'UI/Inflight/ActiveItem/SelectedItemSecurity',
                        secStatus=sec)
            blue.pyos.BeNice()
        corpID = None
        charID = None
        categoryID = None
        bountyItemID = None
        bountyTypeID = None
        bountySlim = None
        displayUtilMenu = False
        if multi > 1:
            text += '<br>' + localization.GetByLabel(
                'UI/Inflight/ActiveItem/MultipleItems', itemCount=multi)
            blue.pyos.BeNice()
        elif multi == 1:
            if slimItems:
                slim = slimItems[0]
                if slim.categoryID == const.categoryShip:
                    if util.IsCharacter(slim.charID):
                        charID = slim.charID
                        categoryID = slim.categoryID
                if slim.categoryID == const.categoryEntity:
                    bountyTypeID = slim.typeID
                elif slim.charID:
                    bountyItemID = slim.charID
                    bountySlim = slim
                killRightID, price = self.bountySvc.GetBestKillRight(
                    slim.charID)
                self.utilMenu.UpdateKillRightInfo(killRightID, price,
                                                  slim.charID, slim.itemID)
                stateSvc = sm.GetService('state')
                if killRightID is not None and not (
                        stateSvc.CheckSuspect(slim)
                        or stateSvc.CheckCriminal(slim)):
                    displayUtilMenu = True
            blue.pyos.BeNice()
        self.sr.utilMenuArea.display = displayUtilMenu
        self.utilMenu.display = displayUtilMenu
        if self.lastIcon != (typeID, itemID, charID):
            uthread.pool('ActiveItem::GetIcon', self.GetIcon, typeID, itemID,
                         charID, corpID, categoryID)
            self.lastIcon = (typeID, itemID, charID)
        else:
            self.sr.iconpar.state = uiconst.UI_PICKCHILDREN
            if categoryID == const.categoryShip and charID:
                self.sr.chariconpar.state = uiconst.UI_PICKCHILDREN
        bountyHint = None
        reducedBountyIndication = None
        if (bountyItemID, bountyTypeID) != self.lastBountyCheck:
            bounty, bountyHint, reducedBountyIndication = self.CheckBounty(
                bountyTypeID, bountySlim)
            blue.pyos.BeNice()
            if bounty:
                self.bounty = localization.GetByLabel('UI/Common/BountyAmount',
                                                      bountyAmount=util.FmtISK(
                                                          bounty, 0))
            else:
                self.bounty = None
            self.lastBountyCheck = (bountyItemID, bountyTypeID)
            self.lastBountyInfo = (bountyHint, reducedBountyIndication)
        else:
            bountyHint, reducedBountyIndication = self.lastBountyInfo
        if self.bounty:
            text += '<br>'
            text += self.bounty
        if reducedBountyIndication:
            text += reducedBountyIndication
        if updateActions:
            self.ReloadActions(slimItems, invItems, fleetMember, fleetSlim)
        else:
            self.CheckActions(1)
        self.SetText(text, bountyHint)
        self.ShowNoSelectedHint()
        blue.pyos.BeNice()
        self.laseUpdateWidth = self.absoluteRight - self.absoluteLeft
        if not self.sr.updateTimer and not invItems:
            self.sr.updateTimer = base.AutoTimer(500, self.UpdateAll)