Jump to content
Menü aufrufen
Toggle preferences menu
Persönliches Menü aufrufen
Nicht angemeldet
Ihre IP-Adresse wird öffentlich sichtbar sein, wenn Sie Änderungen vornehmen.

Die Dokumentation für dieses Modul kann unter Modul:Entity/Item/doc erstellt werden

require('strict')

--- @module Entity/Item
--- Item type module. Extends Base with item-specific properties
--- (size, mass, volume) and the shared item API endpoint.

local format = require('Module:Entity/Format')
local base = require('Module:Entity/Base')
local subtypeResolver = require('Module:Entity/SubtypeResolver')
local acq = require('Module:Entity/Acquisition')
local yesno = require('Module:Yesno')
local msg = require('Module:Entity/Message').msg
local noun = require('Module:Entity/Message').noun

local p = {}

--- Canonical kind name, exposed as Data.get(args).kind (non-empty and
--- unique, enforced by the Registry conformance test).
p.name = 'Item'

--- An item page with no manufacturer, from the record or |manufacturer=, is
--- tracked as missing one (Module:Entity/Categories).
p.hasManufacturer = true

--- @type string
p.parent = 'Entity/Base'

--- Maps API type strings to item subtype leaf loaders (see Module:Entity/SubtypeResolver). Lives in Item
--- (not in Data.lua) because subtype dispatch is an item-internal
--- concern — Data.lua only needs to know "ask the kind to resolve its
--- own subtype". Add new entries here when creating new item subtypes.
---
--- Food / Drink are intentionally absent: they are handled by the
--- data-driven consumable facet (Module:Entity/Facet/Consumable), not a
--- subtype leaf. Their subtitle + category still resolve via types.json.
local itemSubtypeMapping = {
	Module = function()
		return require('Module:Entity/Item/Module')
	end,
	Turret = function()
		return require('Module:Entity/Item/Turret')
	end,
	WeaponPersonal = function()
		return require('Module:Entity/Item/WeaponPersonal')
	end,
	WeaponAttachment = function()
		return require('Module:Entity/Item/WeaponAttachment')
	end,
	FPS_Consumable = function()
		return require('Module:Entity/Item/FPSConsumable')
	end,
	Misc = function()
		return require('Module:Entity/Item/Misc')
	end,
	WeaponGun = function()
		return require('Module:Entity/Item/WeaponGun')
	end,
	PowerPlant = function()
		return require('Module:Entity/Item/PowerPlant')
	end,
	Cooler = function()
		return require('Module:Entity/Item/Cooler')
	end,
	Shield = function()
		return require('Module:Entity/Item/Shield')
	end,
	QuantumDrive = function()
		return require('Module:Entity/Item/QuantumDrive')
	end,
	JumpDrive = function()
		return require('Module:Entity/Item/JumpModule')
	end,
	Radar = function()
		return require('Module:Entity/Item/Radar')
	end,
	EMP = function()
		return require('Module:Entity/Item/EMP')
	end,
	QuantumInterdictionGenerator = function()
		return require('Module:Entity/Item/QuantumInterdictionGenerator')
	end,
	FlightController = function()
		return require('Module:Entity/Item/FlightController')
	end,
	Missile = function()
		return require('Module:Entity/Item/Missile')
	end,
	WeaponMissile = function()
		return require('Module:Entity/Item/Missile')
	end,
	Bomb = function()
		return require('Module:Entity/Item/Bomb')
	end,
	MissileLauncher = function()
		return require('Module:Entity/Item/Rack')
	end,
	BombLauncher = function()
		return require('Module:Entity/Item/Rack')
	end,
	TractorBeam = function()
		return require('Module:Entity/Item/Beam')
	end,
	TowingBeam = function()
		return require('Module:Entity/Item/Beam')
	end,
	MiningModifier = function()
		return require('Module:Entity/Item/MiningModule')
	end,
	WeaponMining = function()
		return require('Module:Entity/Item/WeaponMining')
	end,
	SalvageModifier = function()
		return require('Module:Entity/Item/Scraper')
	end,
	SalvageHead = function()
		return require('Module:Entity/Item/SalvageHead')
	end,
}

--- Formats a short description using the item-family template:
--- "[<prefix>] <type> [by <manufacturer>]". Subtypes (Food, Drink, etc.) can
--- call this to compose a description that matches the item aesthetic, or
--- bypass it entirely and return a custom string from getShortDescription.
---
--- @param typeInfo table
--- @param apiData table
--- @param args table
--- @param prefix string|nil Adjective to prepend (e.g. effect). Cased automatically.
--- @return string
function p.formatShortDescription(typeInfo, apiData, args, prefix)
	-- msg() only: a dataset hit swaps in the German noun with its capitals, and
	-- the English fallback keeps the type map's spelling.
	local desc = msg(typeInfo.name)
	if prefix then
		-- A trailing '-' marks a pre-localized compound stem (e.g. the
		-- consumable facet's effects); anything else localizes through msg().
		local localized = prefix:sub(-1) == '-' and prefix or msg(prefix)
		if localized ~= prefix or prefix:sub(-1) == '-' then
			-- A trailing '-' on the localized value joins without the space the
			-- English adjective form uses ("Toxisch-Lebensmittel").
			local joiner = localized:sub(-1) == '-' and '' or ' '
			desc = localized .. joiner .. noun(desc)
		else
			local lowered = prefix:lower()
			desc = lowered:sub(1, 1):upper() .. lowered:sub(2) .. ' ' .. desc:lower()
		end
	end
	local manufacturer = base.resolveManufacturer(apiData, args)
	if manufacturer then
		desc = desc .. ' ' .. msg('manufactured by') .. ' ' .. manufacturer.name
	end
	return desc
end

--- @return EntityApiConfig[]
function p.getApiConfigs()
	return {
		{
			name = 'StarCitizenWikiAPI',
			endpoint = 'items/%s',
			-- `ports` is required so turret / weapon-mount items carry the embedded
			-- equipped gun's `vehicle_weapon` (Entity/Item/Turret reads it) and so
			-- Entity/Ports gets full port detail on item pages. Without it the API
			-- returns a shallow ports array (no port `type`, no `vehicle_weapon`).
			-- de_DE delivers the description in German; every machine-compared
			-- field on this endpoint (class_name, type, size, grade, class,
			-- category_label) is locale-invariant, so no ingest aliases are needed.
			params = { locale = 'de_DE', include = 'related_items,blueprints,vehicles,ports' },
			responseDataPath = 'data',
		},
	}
end

--- Positive identification for items, independent of probe order. Items carry no
--- type-kind flag the way vehicles carry `is_vehicle`, so identity rests on
--- `class_name`: every item record has one, and no commodity, mission, blueprint
--- or starmap-location record does. Vehicles carry `class_name` too, hence the
--- `is_vehicle` exclusion — the one cross-kind fact this test encodes, and the
--- same one the API asserts by redirecting a vehicle UUID off `items/`.
---
--- Order-independence matters: the declared-kind gate in Module:Entity/Data
--- offers a record of *any* kind to a single kind's matches() (a vehicle uuid
--- pasted into an item page), and the probe's items endpoint answers a vehicle
--- uuid with the vehicle record when redirects are followed. A looser "has a
--- uuid" test would claim both.
---
--- @param apiData table|nil
--- @return boolean
function p.matches(apiData)
	return apiData ~= nil and apiData.uuid ~= nil and apiData.class_name ~= nil and apiData.is_vehicle == nil
end

--- Refines the leaf module from the kind module to a subtype leaf
--- (Food / Drink / WeaponPersonal) when the API `type` matches a
--- known mapping. Returns nil for unknown or missing types, which
--- means "no refinement — use the Item module itself as the leaf."
--- Module:Entity/Data invokes this after kind dispatch.
---
--- @param apiData table|nil
--- @param args table|nil  Unused (item subtype dispatches on apiData.type); present for kind-contract parity.
--- @return table|nil The resolved subtype module, or nil
function p.resolveSubtype(apiData, args)
	return subtypeResolver.resolve(apiData and apiData.type, itemSubtypeMapping)
end

--- Class (Military / Civilian / Industrial / Competition / ...) is populated
--- only on graded vehicle components; vehicle weapons and FPS items have
--- none. Returns nil when absent so the row collapses.
---
--- @param apiData table
--- @return string|nil
local function classContent(apiData)
	local class = apiData.class
	if type(class) == 'string' and class ~= '' then
		return class
	end
	return nil
end

--- Grade (A-D) is meaningful only on graded vehicle components - those the
--- API marks with a `class`. Vehicle weapons report a constant grade 'A'
--- with no class, and FPS items have no grade; both get no row. Gating on
--- `class` keeps the constant 'A' off every weapon.
---
--- @param apiData table
--- @return string|nil
local function gradeContent(apiData)
	if classContent(apiData) == nil then
		return nil
	end
	local grade = apiData.grade
	if grade == nil or grade == '' then
		return nil
	end
	return tostring(grade)
end

--- Extracts the in-game "Item Type" label from an entity's description_data
--- (e.g. "Laser Repeater"). This is the specific item type as shown in-game,
--- distinct from the API `type` (WeaponGun) and `sub_type` (Gun) fields.
--- Returns nil when absent.
---
--- @param apiData table|nil
--- @return string|nil
local function getItemType(apiData)
	local descData = apiData and apiData.description_data
	if type(descData) ~= 'table' then
		return nil
	end
	for _, entry in ipairs(descData) do
		if entry.name == 'Item Type' or entry.name == 'Type' then
			return entry.value or entry.type
		end
	end
	return nil
end

--- Extracts an item's volume from `apiData.dimension`, normalized to µSCU
--- (microSCU) as a number. Reads `volume_converted` + `volume_converted_unit`
--- (the precision-preserving pair the API uses for display) rather than the
--- raw `dimension.volume` field — that one rounds to 0 for sub-SCU items
--- like a 1 µSCU PDC. Returns nil when there's no volume data or when the
--- unit is something we don't recognize (refuse rather than guess).
---
--- Matches the display code in treating a missing `volume_converted_unit` as SCU.
---
--- @param apiData table|nil
--- @return number|nil  volume in µSCU
local function getVolume(apiData)
	local dim = apiData and apiData.dimension
	if type(dim) ~= 'table' then
		return nil
	end
	local v = tonumber(dim.volume_converted)
	if not v then
		return nil
	end
	local unit = dim.volume_converted_unit or 'SCU'
	if unit == 'SCU' then
		return math.floor(v * 1000000 + 0.5)
	end
	if unit == 'µSCU' then
		return v
	end
	return nil
end

--- @param ctx EntityHookContext
--- @return table[] Ordered list of section entries with key field
function p.getSections(ctx)
	local apiData, args = ctx.apiData, ctx.args
	local manufacturer = base.resolveManufacturer(apiData, args)
	local manufacturerLink = nil
	if manufacturer then
		if manufacturer.page == manufacturer.name then
			manufacturerLink = '[[' .. manufacturer.name .. ']]'
		else
			manufacturerLink = '[[' .. manufacturer.page .. '|' .. manufacturer.name .. ']]'
		end
	end

	-- Volume, mass, and the dimension diagram are now rendered by the dimension
	-- facet (Module:Entity/Facet/Dimensions) as a section above Metadata.
	return {
		{
			key = 'general',
			items = {
				{
					label = msg('Manufacturer'),
					content = manufacturerLink,
				},
				{ label = msg('Size'), content = apiData.size and tostring(apiData.size) },
				{ label = msg('Class'), content = msg(classContent(apiData)) },
				{ label = msg('Grade'), content = gradeContent(apiData) },
			},
		},
	}
end

--- Spec-style short description for graded vehicle components — the ones the
--- API marks with a `class` (power plants, coolers, shields, quantum drives,
--- ...): e.g. "S3 Gr. A military power plant by Amon & Reese Co.". Returns nil
--- when the item isn't a graded component (missing class, grade, or size), so
--- the caller falls back to the generic item descriptor. Gating on classContent
--- keeps this off vehicle weapons and FPS items, which carry no class.
---
--- @param typeInfo table
--- @param apiData table
--- @param args table
--- @return string|nil
function p.formatGradedShortDescription(typeInfo, apiData, args)
	local manufacturer = base.resolveManufacturer(apiData, args)
	return format.gradedShortDescription(
		typeInfo.name,
		apiData.size,
		classContent(apiData),
		gradeContent(apiData),
		manufacturer and manufacturer.name or nil
	)
end

--- Default short description for items: graded vehicle components get the
--- spec-style descriptor (formatGradedShortDescription); everything else gets
--- "[<prefix>] <type> hergestellt von <manufacturer>". The optional prefix is supplied by
--- a matching facet (e.g. the consumable facet's effects adjective) and composed
--- by formatShortDescription.
---
--- @param ctx EntityHookContext
--- @return string
function p.getShortDescription(ctx)
	local apiData, args, typeInfo, prefix = ctx.apiData, ctx.args, ctx.typeInfo, ctx.prefix
	return p.formatGradedShortDescription(typeInfo, apiData, args)
		or p.formatShortDescription(typeInfo, apiData, args, prefix)
end

--- Ship-component check for the compound (Größe N) browse category: FPS
--- items (drinks, magazines, personal weapons) also carry an API `size`, but
--- it is stack/weapon-slot noise there, not an equipment class, so they get
--- no size category. The stored Größe is ungated.
---
--- @param apiData table
--- @return number|nil
local function shipSize(apiData)
	local classification = apiData and apiData.classification
	if type(classification) ~= 'string' or classification:sub(1, 5) ~= 'Ship.' then
		return nil
	end
	return tonumber(apiData.size)
end

--- Compound size browse category ("<Kategorie> (Größe N)"), the legacy wiki's
--- own scheme (Kategorie:Rakete (Größe 1)); grade deliberately gets no
--- category. Returns only the compound: deriveCategories already emits the
--- structural category from typeInfo.
---
--- @param ctx EntityHookContext
--- @return string[]|nil
function p.getCategories(ctx)
	local apiData, typeInfo = ctx.apiData, ctx.typeInfo
	local size = shipSize(apiData)
	local base = typeInfo and (typeInfo.category or typeInfo.name)
	if size == nil or type(base) ~= 'string' or base == '' then
		return nil
	end
	return { base .. ' (Größe ' .. tostring(size) .. ')' }
end

--- An item's base-variant flag (`is_base_variant`): true for the canonical
--- piece, false for a colorway / edition variant of it. Returned only when the
--- API carries the boolean (most items do), so items without the concept store
--- nothing. A generic item facet — it lets index tables filter the colorway
--- explosion (armor / clothing) down to base pieces.
---
--- @param apiData table
--- @return boolean|nil
local function baseVariant(apiData)
	if type(apiData.is_base_variant) == 'boolean' then
		return apiData.is_base_variant
	end
	return nil
end

--- Contributes item-level facet values to structured data: size, grade,
--- class, the in-game item type, volume (in µSCU), the base-variant flag, and
--- the rarity tier. Stored backend-agnostically via Module:Entity/StructuredData.
--- These are facets for querying/tooling, not browse categories — the structural
--- category is classification-driven (Module:Entity/Data.resolveClassification →
--- classifications.json).
---
--- @param ctx EntityHookContext
--- @return table<string, any>
function p.getStructuredData(ctx)
	local apiData = ctx.apiData
	return {
		size = tonumber(apiData.size),
		grade = apiData.grade,
		class = apiData.class,
		item_type = getItemType(apiData),
		volume = getVolume(apiData),
		base_variant = baseVariant(apiData),
		rarity = apiData.rarity,
	}
end

--- @param ctx EntityHookContext
--- @return EntityItemData[] External site items contributed by this module
function p.getExternalSiteItems(ctx)
	local apiData, args = ctx.apiData, ctx.args
	local siteDefs = mw.loadJsonData('Module:Entity/Item/communitySites.json')
	local links = format.buildSiteLinks(siteDefs, {
		uuid = args.uuid,
		name = args.name or apiData.name,
	})
	if not links then
		return {}
	end
	return { { label = msg('Community sites'), content = links } }
end

--- Acquisition data for {{Entity/Availability}}: Buy/Loot/Craft/Pledge summary
--- flags (+ Rent only when the editor sets it — items aren't structurally
--- rentable) and a single Shops terminal card from uex_prices.purchase.
--- @param ctx EntityHookContext
--- @return { summary: table[], cards: table[] }
function p.getAcquisition(ctx)
	local apiData, args = ctx.apiData, ctx.args
	local prices = type(apiData.uex_prices) == 'table' and apiData.uex_prices or {}
	local purchase = type(prices.purchase) == 'table' and prices.purchase or {}

	local summary = {
		{
			label = msg('Buy'),
			icon = '🛒',
			value = acq.resolveFlag(args.canBuy, acq.inferCanAcquire(purchase, 'price_buy')),
		},
	}
	local rentValue = yesno(args.canRent)
	if rentValue ~= nil then
		summary[#summary + 1] = { label = msg('Rent'), icon = '⏳', value = rentValue }
	end
	summary[#summary + 1] =
		{ label = msg('Loot'), icon = '📦', value = acq.resolveFlag(args.canLoot, apiData.is_lootable) }
	summary[#summary + 1] =
		{ label = msg('Craft'), icon = '🔨', value = acq.resolveFlag(args.canCraft, apiData.is_craftable) }
	summary[#summary + 1] = {
		label = 'Pledge',
		icon = '💵',
		value = acq.resolveFlag(
			args.canPledge,
			acq.hasEntityTag(apiData, 'PromotionalItem') or acq.hasEntityTag(apiData, 'SubscriberFlair')
		),
	}

	local hasPurchase = #purchase > 0
	local hasSell = hasPurchase and acq.priceRange(purchase, 'price_sell') ~= nil
	local priceColumns = { { id = 'buy', key = 'price_buy', label = msg('Buy') } }
	if hasSell then
		priceColumns[#priceColumns + 1] = { id = 'sell', key = 'price_sell', label = msg('Sell') }
	end
	local description
	if hasPurchase then
		description = hasSell and acq.buildShopTerminalsDescription(purchase)
			or acq.buildSinglePriceDescription(purchase, 'price_buy')
	else
		description = msg('No shop data in UEX')
	end

	return {
		summary = summary,
		cards = {
			{
				type = 'terminals',
				title = '<span aria-hidden="true">🛒</span> Shops',
				caption = msg('Shop terminals'),
				description = description,
				prices = hasPurchase and purchase or nil,
				priceColumns = priceColumns,
			},
		},
	}
end

-- Test-only exports. Not part of the public API.
p._internal = {
	classContent = classContent,
	gradeContent = gradeContent,
	getItemType = getItemType,
	getVolume = getVolume,
}

return p
Zuletzt geändert
Urheberrecht
Cookies helfen uns bei der Bereitstellung dieses Wikis. Durch die Nutzung des Star Citizen Wiki erklärst du dich damit einverstanden, dass wir Cookies speichern.