Модуль:Color contrast: различия между версиями

Материал из Энциклопедия автомобильных номеров мира
Перейти к навигации Перейти к поиску
м (Защищена страница «Шаблон:-» [edit=sysop:move=sysop])
 
м (7 версий импортировано: Шаблон Ampbox и товарищи Википедия)
 
(не показано 8 промежуточных версий 7 участников)
Строка 1: Строка 1:
{{к-у}}
--
{{о|автомобильных номерах Турецкой Республики Северного Кипра|Автомобильные номера ТРСК}}
-- This module implements
{{о|автомобильных номерах на британских базах Акротири и Декелия|Автомобильные номера на базах Акротири и Декелия}}
--  {{Color contrast ratio}}
{{о|автомобильных номерах ООН на Кипре|Автомобильные номера буферной зоны ООН на Кипре}}
--  {{Greater color contrast ratio}}
{{Номер
-- {{ColorToLum}}
|название                  = Автомобильные номера Кипра стандарта 2013 года
-- {{RGBColorToLum}}
|название страны            = Республика Кипр
--
|изображение                = Cyprus license plate 2013 sample.svg
local p = {}
|ширина                    = 400px
local HTMLcolor = mw.loadData( 'Module:Color contrast/colors' )
  |описание изображения      = Автомобильный номер Кипра<br/>стандарта 2013 года
|страна                    = Кипр
|стандарт                  =
|дата ввода стандарта      = 2013, 1990
|Резерв00                  =
|Резерв01                  =
|Резерв02                  =
|дата упразднения стандарта =
|Резерв03                  =
|материал                  = пластик, металл
|ширина номера              = 520 мм
|высота номера              = 110 мм
|ширина 2ст номера          =
|высота 2ст номера          =
|размеры других типов      =
|цвет фона                  = {{Фон|Кипр|Белый фон|Жёлтый фон|Чёрный фон|Красный фон|Синий фон}}
  |цвет шрифта                = {{Шрифт|Кипр|ЧШ|БШ|Красный шрифт}}
|сайт                      =
|разное                    =
|предыдущий стандарт        =  
|следующий стандарт        =  
}}
[[Файл:EU-section-with-CY.svg|100px|thumb|left|Европоле с кодом Кипра «CY»]]
'''Автомобильные номера Кипра''' — металлическая или пластиковая пластина, устанавливаемая на транспортное средство при его регистрации. Номерные знаки в Кипре имеют чёрный шрифт на белом фоне. На номерах используется [[FE-Schrift]].


== История ==
local function sRGB ( v )
{| class="float-right infobox" style="border:2px solid grey;WIDTH:100px;"
if (v <= 0.03928) then
|- style="background-color:#EEE"
v = v / 12.92
| История номеров Кипра:
else
|-
v = math.pow((v+0.055)/1.055, 2.4)
|'''С 1930 до 1950'''
end
{{Nummernschild|BORDER=#CCCCCC|BACK=#000000|COLOR=#CCCCCC|1234|WIDTH=100px}}
return v
end


'''С 1950 до 1956'''
local function rgbdec2lum( R, G, B )
{{Nummernschild|BORDER=#CCCCCC|BACK=#000000|COLOR=#CCCCCC|A 123|WIDTH=100px}}
if ( 0 <= R and R < 256 and 0 <= G and G < 256 and 0 <= B and B < 256 ) then
return 0.2126 * sRGB(R/255) + 0.7152 * sRGB(G/255) + 0.0722 * sRGB(B/255)
else
return ''
end
end


'''С 1956 до 1973'''
local function hsl2lum( h, s, l )
{{Nummernschild|BORDER=#CCCCCC|BACK=#000000|COLOR=#CCCCCC|AB 123|WIDTH=100px}}
if ( 0 <= h and h < 360 and 0 <= s and s <= 1 and 0 <= l and l <= 1 ) then
local c = (1 - math.abs(2*l - 1))*s
local x = c*(1 - math.abs( math.fmod(h/60, 2) - 1) )
local m = l - c/2


'''С 1973 до 1990'''
local r, g, b = m, m, m
{{Nummernschild|BORDER=#CCCCCC|AB 123|WIDTH=100px}} и {{Nummernschild|BORDER=#FFD103|BACK=#FFD103|AB 123|WIDTH=100px}}
if( 0 <= h and h < 60 ) then
r = r + c
g = g + x
elseif( 60 <= h and h < 120 ) then
r = r + x
g = g + c
elseif( 120 <= h and h < 180 ) then
g = g + c
b = b + x
elseif( 180 <= h and h < 240 ) then
g = g + x
b = b + c
elseif( 240 <= h and h < 300 ) then
r = r + x
b = b + c
elseif( 300 <= h and h < 360 ) then
r = r + c
b = b + x
end
return rgbdec2lum(255*r, 255*g, 255*b)
else
return ''
end
end


'''С 1990 до 2004'''
local function color2lum( c )
{{Nummernschild|BORDER=#CCCCCC|ABC 123|WIDTH=100px}} и {{Nummernschild|BORDER=#FFD103|BACK=#FFD103|ABC 123|WIDTH=100px}}


'''С 2003 до 2013:'''
if (c == nil) then
{{Euro-Nummernschild|BORDER=#CCCCCC|[[File:EU-section-with-CY.svg|x20px]]|ABC 123|WIDTH=100px}}
return ''
и
end
{{Euro-Nummernschild|BACK=#FFD103|[[File:EU-section-with-CY.svg|x20px]]|ABC 123|WIDTH=100px}}
-- whitespace
c = c:match( '^%s*(.-)[%s;]*$' )


'''С 2013:'''
-- lowercase
{{Euro-Nummernschild|BORDER=#CCCCCC|[[File:EU-section-with-CY.svg|x20px]]|ABC 123|WIDTH=100px}}
c = c:lower()
|}


Истоки кипрских номерных знаков лежат в [[Автомобильные номера Великобритании|британской системе]]. В начале на чёрной пластине использовалась белая или серебристая надпись; позже цветовая гамма была изменена на чёрно-желтый (сзади) или на чёрно-белый (спереди). Комбинация состояла не более чем из четырёх цифр, после 1950 года номер дополнился буквой и исчезла одна цифра. В 1956 году была добавлена ещё одна буква. На основе двух последовательных букв можно было сделать вывод о годе регистрации автомобиля. В 1990 году была достигнута комбинация YZ. В результате структура была изменена на ABC 123, причем первая буква обозначала год приема (a = 1990/91, B = 1992, C = 1993, D = 1994).
-- first try to look it up
Начиная с 1995 года, с серии EAA номера выдавались независимо от года. С этой даты используются только двенадцать букв, которые встречаются как в латинском, так и в греческом алфавите: A, B, E, H, K, M, N, P, T, X, Y и Z.
local L = HTMLcolor[c]
if (L ~= nil) then
return L
end


С 1973 по 2004 год номерные знаки были изготовлены из пластика, позже — из металла. С момента вступления в ЕС на левом краю появилось синее европоле с буквами «CY».
  -- convert from hsl
  if mw.ustring.match(c,'^hsl%([%s]*[0-9][0-9%.]*[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*%)$') then
local h, s, l = mw.ustring.match(c,'^hsl%([%s]*([0-9][0-9%.]*)[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*%)$')
return hsl2lum(tonumber(h), tonumber(s)/100, tonumber(l)/100)
  end


Начиная с 3 июня 2013 года выпускаются новые регистрационные знаки, после реформы системы нумерации. Основной цвет заднего номерного знака был изменен на белый. В настоящее время между буквами и цифрами появляется месяц и год первоначальной регистрации транспортного средства в Республике Кипр. Обязательства по общему обмену старых на новые номерные знаки нет. Только некоторые категории транспортных средств должны были заменить старые номерные знаки до 3 декабря 2013 года.
  -- convert from rgb
  if mw.ustring.match(c,'^rgb%([%s]*[0-9][0-9]*[%s]*,[%s]*[0-9][0-9]*[%s]*,[%s]*[0-9][0-9]*[%s]*%)$') then
local R, G, B = mw.ustring.match(c,'^rgb%([%s]*([0-9][0-9]*)[%s]*,[%s]*([0-9][0-9]*)[%s]*,[%s]*([0-9][0-9]*)[%s]*%)$')
return rgbdec2lum(tonumber(R), tonumber(G), tonumber(B))
  end


Для старых номерных знаков варьировались размер и дизайн, но обычно использовался шрифт британских номерных знаков. С вступлением в ЕС размер был нормирован и в основном используется вариант немецкого [[DIN-1451|шрифта DIN]]. Текущие знаки используют [[FE-Schrift|шрифт FE]], также разработанный в Германии.
  -- convert from rgb percent
  if mw.ustring.match(c,'^rgb%([%s]*[0-9][0-9%.]*%%[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*%)$') then
local R, G, B = mw.ustring.match(c,'^rgb%([%s]*([0-9][0-9%.]*)%%[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*%)$')
return rgbdec2lum(255*tonumber(R)/100, 255*tonumber(G)/100, 255*tonumber(B)/100)
  end


Старые номера удаляются из регистра, комбинация цифр больше не выдаётся. Пластины могут быть сохранены владельцем автомобиля в качестве сувенира.
-- remove leading # (if there is one) and whitespace
c = mw.ustring.match(c, '^[%s#]*([a-f0-9]*)[%s]*$')


До разделения острова Кипр в 1974 году использовалась единая система номерных знаков, которая продолжалась Республикой Кипр на юге до 1990 года, а непризнанная на международном уровне [[Автомобильные номера Турецкой Республики Северного Кипра|Турецкая Республика Северного Кипра использует её до сих пор]].
-- split into rgb
local cs = mw.text.split(c or '', '')
if( #cs == 6 ) then
local R = 16*tonumber('0x' .. cs[1]) + tonumber('0x' .. cs[2])
local G = 16*tonumber('0x' .. cs[3]) + tonumber('0x' .. cs[4])
local B = 16*tonumber('0x' .. cs[5]) + tonumber('0x' .. cs[6])


=Специальные номера=
return rgbdec2lum(R, G, B)
===Номера для дилеров===
elseif ( #cs == 3 ) then
'''1973-1990'''
local R = 16*tonumber('0x' .. cs[1]) + tonumber('0x' .. cs[1])
{{Nummernschild|BORDER=#ff0000|BACK=#FFFFFF|COLOR=#FF0000|DL 123|WIDTH=100px}}
local G = 16*tonumber('0x' .. cs[2]) + tonumber('0x' .. cs[2])
local B = 16*tonumber('0x' .. cs[3]) + tonumber('0x' .. cs[3])


'''1990–н.в.'''
return rgbdec2lum(R, G, B)
{{Nummernschild|BORDER=#ff0000|BACK=#FFFFFF|COLOR=#FF0000|<small>ΔΟΚΙΜΗ</small> 123-456|WIDTH=100px}}
end


Надпись красным ΔΟΚΙΜΗ («тест») на белой пластине и две группы цифр, первая группа — цифровой код продавца, вторая — номер пластины. Единственные официально централизовано выпускаемые номера на Кипре. Раньше они были того же формата, что и гражданские машины, но использовали код «DL» и красные буквы вместо чёрных.
-- failure, return blank
return ''
end


===Номера для прокатных автомобилей===
function p._greatercontrast(args)
'''1973-1990'''
local bias = tonumber(args['bias'] or '0') or 0
{{Nummernschild|BORDER=#000000|BACK=#8b0000|COLOR=#000000|ZAB 123|WIDTH=100px}}
local v1 = color2lum(args[1] or '')
'''1990-2013'''
local c2 = args[2] or '#FFFFFF'
{{Nummernschild|BORDER=#000000|BACK=#8b0000|COLOR=#000000|ZABC 123|WIDTH=100px}}
local v2 = color2lum(c2)
'''2013–н.в.'''
local c3 = args[3] or '#000000'
{{Euro-Nummernschild|BORDER=#000000|BACK=#8b0000|COLOR=#000000|[[File:EU-section-with-CY.svg|x20px]]|ABC 123|WIDTH=100px}}
local v3 = color2lum(c3)
Состоит из трёх букв и трёх цифр (например, ABC123) с тёмно-красным фоном. До 2013 года начинались с буквы ''Z''
local ratio1 = 0;
local ratio2 = 0;
if (type(v1) == 'number' and type(v2) == 'number') then
ratio1 = (v2 + 0.05)/(v1 + 0.05)
ratio1 = (ratio1 < 1) and 1/ratio1 or ratio1
end
if (type(v1) == 'number' and type(v3) == 'number') then
ratio2 = (v3 + 0.05)/(v1 + 0.05)
ratio2 = (ratio2 < 1) and 1/ratio2 or ratio2
end
return (ratio1 + bias > ratio2) and c2 or c3
end


== Примечания ==
function p._ratio(args)
{{примечания}}
local v1 = color2lum(mw.text.unstripNoWiki(args[1] or ''))
{{Автомобильные номера Европы|Кипр}}
local v2 = color2lum(mw.text.unstripNoWiki(args[2] or ''))
{{Автомобильные номера Азии|Кипр}}
if (type(v1) == 'number' and type(v2) == 'number') then
-- v1 should be the brighter of the two.
if v2 > v1 then
v1, v2 = v2, v1
end
return (v1 + 0.05)/(v2 + 0.05)
else
return args['error'] or '?'
end
end
 
function p._styleratio(args)
local style = (args[1] or ''):lower()
local bg, fg = 'white', '#202122'
local lum_bg, lum_fg = 1, 0.016
 
if args[2] then
local lum = color2lum(args[2])
if lum ~= '' then bg, lum_bg = args[2], lum end
end
if args[3] then
local lum = color2lum(args[3])
if lum ~= '' then fg, lum_fg = args[3], lum end
end
 
local slist = mw.text.split(style or '', ';')
for k = 1, #slist do
local s = slist[k]
local k, v = s:match( '^[%s]*([^:]-):([^:]-)[%s;]*$' )
k = k or ''
v = v or ''
if (k:match('^[%s]*(background)[%s]*$') or k:match('^[%s]*(background%-color)[%s]*$')) then
local lum = color2lum(v)
if( lum ~= '' ) then bg, lum_bg = v, lum end
elseif (k:match('^[%s]*(color)[%s]*$')) then
local lum = color2lum(v)
if( lum ~= '' ) then bg, lum_fg = v, lum end
end
end
if lum_bg > lum_fg then
return (lum_bg + 0.05)/(lum_fg + 0.05)
else
return (lum_fg + 0.05)/(lum_bg + 0.05)
end
end
 
function p.lum(frame)
return color2lum(frame.args[1] or frame:getParent().args[1])
end
 
function p.ratio(frame)
local args = frame.args[1] and frame.args or frame:getParent().args
return p._ratio(args)
end
 
function p.styleratio(frame)
local args = frame.args[1] and frame.args or frame:getParent().args
return p._styleratio(args)
end
 
function p.greatercontrast(frame)
local args = frame.args[1] and frame.args or frame:getParent().args
return p._greatercontrast(args)
end
 
return p

Текущая версия от 14:04, 26 апреля 2021

Модуль обеспечивает работу шаблона {{цветовой контраст}}, также используется в модуле Navbox.

Использования

Модуль может использоваться либо напрямую, либо через шаблон {{цветовой контраст}}:

{{цветовой контраст|цвет1|цвет2|error=?}} или {{#invoke:Color contrast|ratio|цвет1|цвет2|error=?}}

Подробнее об использовании шаблона см. его документацию.


--
-- This module implements 
--  {{Color contrast ratio}}
--  {{Greater color contrast ratio}}
--  {{ColorToLum}}
--  {{RGBColorToLum}}
--
local p = {}
local HTMLcolor = mw.loadData( 'Module:Color contrast/colors' )

local function sRGB ( v ) 
	if (v <= 0.03928) then 
		v = v / 12.92
	else
		v = math.pow((v+0.055)/1.055, 2.4)
	end
	return v
end

local function rgbdec2lum( R, G, B )
	if ( 0 <= R and R < 256 and 0 <= G and G < 256 and 0 <= B and B < 256 ) then
		return 0.2126 * sRGB(R/255) + 0.7152 * sRGB(G/255) + 0.0722 * sRGB(B/255)
	else
		return ''
	end
end

local function hsl2lum( h, s, l )
	if ( 0 <= h and h < 360 and 0 <= s and s <= 1 and 0 <= l and l <= 1 ) then
		local c = (1 - math.abs(2*l - 1))*s
		local x = c*(1 - math.abs( math.fmod(h/60, 2) - 1) )
		local m = l - c/2

		local r, g, b = m, m, m
		if( 0 <= h and h < 60 ) then
			r = r + c
			g = g + x
		elseif( 60 <= h and h < 120 ) then
			r = r + x
			g = g + c
		elseif( 120 <= h and h < 180 ) then
			g = g + c
			b = b + x
		elseif( 180 <= h and h < 240 ) then
			g = g + x
			b = b + c
		elseif( 240 <= h and h < 300 ) then
			r = r + x
			b = b + c
		elseif( 300 <= h and h < 360 ) then
			r = r + c
			b = b + x
		end
		return rgbdec2lum(255*r, 255*g, 255*b)
	else
		return ''
	end
end

local function color2lum( c )

	if (c == nil) then
		return ''
	end
	-- whitespace
	c = c:match( '^%s*(.-)[%s;]*$' )

	-- lowercase
	c = c:lower()

	-- first try to look it up
	local L = HTMLcolor[c]
	if (L ~= nil) then
		return L
	end

   	-- convert from hsl
   	if mw.ustring.match(c,'^hsl%([%s]*[0-9][0-9%.]*[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*%)$') then
		local h, s, l = mw.ustring.match(c,'^hsl%([%s]*([0-9][0-9%.]*)[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*%)$')
		return hsl2lum(tonumber(h), tonumber(s)/100, tonumber(l)/100)
   	end

   	-- convert from rgb
   	if mw.ustring.match(c,'^rgb%([%s]*[0-9][0-9]*[%s]*,[%s]*[0-9][0-9]*[%s]*,[%s]*[0-9][0-9]*[%s]*%)$') then
		local R, G, B = mw.ustring.match(c,'^rgb%([%s]*([0-9][0-9]*)[%s]*,[%s]*([0-9][0-9]*)[%s]*,[%s]*([0-9][0-9]*)[%s]*%)$')
		return rgbdec2lum(tonumber(R), tonumber(G), tonumber(B))
   	end

   	-- convert from rgb percent
   	if mw.ustring.match(c,'^rgb%([%s]*[0-9][0-9%.]*%%[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*,[%s]*[0-9][0-9%.]*%%[%s]*%)$') then
		local R, G, B = mw.ustring.match(c,'^rgb%([%s]*([0-9][0-9%.]*)%%[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*,[%s]*([0-9][0-9%.]*)%%[%s]*%)$')
		return rgbdec2lum(255*tonumber(R)/100, 255*tonumber(G)/100, 255*tonumber(B)/100)
   	end

	-- remove leading # (if there is one) and whitespace
	c = mw.ustring.match(c, '^[%s#]*([a-f0-9]*)[%s]*$')

	-- split into rgb
	local cs = mw.text.split(c or '', '')
	if( #cs == 6 ) then
		local R = 16*tonumber('0x' .. cs[1]) + tonumber('0x' .. cs[2])
		local G = 16*tonumber('0x' .. cs[3]) + tonumber('0x' .. cs[4])
		local B = 16*tonumber('0x' .. cs[5]) + tonumber('0x' .. cs[6])

		return rgbdec2lum(R, G, B)
	elseif ( #cs == 3 ) then
		local R = 16*tonumber('0x' .. cs[1]) + tonumber('0x' .. cs[1])
		local G = 16*tonumber('0x' .. cs[2]) + tonumber('0x' .. cs[2])
		local B = 16*tonumber('0x' .. cs[3]) + tonumber('0x' .. cs[3])

		return rgbdec2lum(R, G, B)
	end

	-- failure, return blank
	return ''
end

function p._greatercontrast(args)
	local bias = tonumber(args['bias'] or '0') or 0
	local v1 = color2lum(args[1] or '')
	local c2 = args[2] or '#FFFFFF'
	local v2 = color2lum(c2)
	local c3 = args[3] or '#000000'
	local v3 = color2lum(c3)
	local ratio1 = 0;
	local ratio2 = 0;
	if (type(v1) == 'number' and type(v2) == 'number') then
		ratio1 = (v2 + 0.05)/(v1 + 0.05)
		ratio1 = (ratio1 < 1) and 1/ratio1 or ratio1
	end
	if (type(v1) == 'number' and type(v3) == 'number') then
		ratio2 = (v3 + 0.05)/(v1 + 0.05)
		ratio2 = (ratio2 < 1) and 1/ratio2 or ratio2
	end
	return (ratio1 + bias > ratio2) and c2 or c3
end

function p._ratio(args)
	local v1 = color2lum(mw.text.unstripNoWiki(args[1] or ''))
	local v2 = color2lum(mw.text.unstripNoWiki(args[2] or ''))
	if (type(v1) == 'number' and type(v2) == 'number') then
		-- v1 should be the brighter of the two.
		if v2 > v1 then
			v1, v2 = v2, v1
		end
		return (v1 + 0.05)/(v2 + 0.05)
	else
		return args['error'] or '?'
	end
end

function p._styleratio(args)
	local style = (args[1] or ''):lower()
	local bg, fg = 'white', '#202122'
	local lum_bg, lum_fg = 1, 0.016

	if args[2] then
		local lum = color2lum(args[2])
		if lum ~= '' then bg, lum_bg = args[2], lum end
	end
	if args[3] then
		local lum = color2lum(args[3])
		if lum ~= '' then fg, lum_fg = args[3], lum end
	end

	local slist = mw.text.split(style or '', ';')
	for k = 1, #slist do
		local s = slist[k]
		local k, v = s:match( '^[%s]*([^:]-):([^:]-)[%s;]*$' )
		k = k or ''
		v = v or ''
		if (k:match('^[%s]*(background)[%s]*$') or k:match('^[%s]*(background%-color)[%s]*$')) then
			local lum = color2lum(v)
			if( lum ~= '' ) then bg, lum_bg = v, lum end
		elseif (k:match('^[%s]*(color)[%s]*$')) then
			local lum = color2lum(v)
			if( lum ~= '' ) then bg, lum_fg = v, lum end
		end
	end
	if lum_bg > lum_fg then
		return (lum_bg + 0.05)/(lum_fg + 0.05)
	else
		return (lum_fg + 0.05)/(lum_bg + 0.05)
	end
end

function p.lum(frame)
	return color2lum(frame.args[1] or frame:getParent().args[1])
end

function p.ratio(frame)
	local args = frame.args[1] and frame.args or frame:getParent().args
	return p._ratio(args)
end

function p.styleratio(frame)
	local args = frame.args[1] and frame.args or frame:getParent().args
	return p._styleratio(args)
end

function p.greatercontrast(frame)
	local args = frame.args[1] and frame.args or frame:getParent().args
	return p._greatercontrast(args)
end

return p