КУПИ КНИГУ ПОЛУЧИ ДЕНЬГИ ОБРАТНО! пр. 11
ДЕННИ РИДДЕЛЛ
MAYA
ДЛЯ WINDOWS И MACINTOSH
authorized training center
VISUAL QUICKSTART GUIDE
mm с
FOR WINDOWS AND MACINTOSH
Danny Riddell
Peachpit Press
Дентр Компьютерного Обучения рекомендует «Alias MAYA 5.0 - это продукт нового поколения систем компьютерной графики для создания потрясающих визуальных эффектов и суперреалистичной ЗО-анимации цифровых персонажей. MAYA представляет собой самые мощные интегрированные программные инструменты трехмерной графики для создания цифрового содержания кино- и видеопродукции, телевизионных передач и заставок, музыкальных клипов и рекламных роликов, компьютерных и видео-игр, презентационной графики и Web-страниц. Эффективный пользовательский интерфейс MAYA, зобравший в себя все лучшие инструментальные средства, открывает компьютерному художнику новые измерения. MAYA - это вселенная, это мир, где даже самые смелые творческие проекты становятся реальностью!»
Нечаев Денис Вячеславович Ведущий преподаватель Центра Компьютерного Обучения по трехмерному моделированию и анимации.
и
юмпыюшюго « Центр Компьютерного Обучения «Специалист» при МГТУ вМТр им. Н. Э. Баумана - крупнейший в России учебный центр, авторизованный ведущими производителями программного обеспечения: Microsoft, Novell, Security Certified Program, CompTIA, Certified Internet Webmaster и др. На сегодняшний день Центр является ведущим учебным центром в области подготовки специалистов по созданию, поддержке и безопасности компьютерных сетей. За 12 лет работы в Центре прошли обучение свыше 120000 человек по более чем 300 различным очным и дистанционным курсам,
Адрес: 105005, Москва, м. Бауманская, Госпитальный пер., д. 4/6 Телефон: (095) 232-3216, 263-6633 E-mail:
[email protected] Internet: www.specialist.ru
QUICK START
IMVflC ДЛЯ WINDOWS И MACINTOSH
Денни Ридделл
Москва, 2004
УДК 004.928 ББК 32.973.26-018.2 Р49 Р49
Ридделл Д. Maya 5 для Windows и Macintosh / Денни Ридделл ; Пер. с англ. Талачева М. И., Осипов А. И. - М.: ДМК Пресс, 2004. - 480 с. : ил. - (Quick Start). ISBN 5-94074-255-6 Maya 5.0 - наиболее мощная и удобная программа трехмерной графики, позволяющая конструировать сложнейшие модели :л создавать реалистичную анимацию. Данная книга в полном объеме содержит информацию, необходимую для освоения этого уникального пакета: описание элементов интерфейса, приемов моделирования и анимации, создания материалов и спецэффектов. Особое внимание уделяется настройке освещения и выполнению визуализации с использованием различных модулей. Кроме того, подробно рассматривается такая сложная и интересная тема, как создание эффектов жидкости. Книга предназначена для начинающих пользователей. Теоретический материал снабжен огромным количеством примеров, что позволяет рекомендовать настоящее издание в качестве справочного пособия. Authorized translation from the Engiish language edition, entitled MAYA 5 FOR WINDOWS AND MACINTOSH: VISUAL QUICKSTART GUIDE, ISBN 0321219201 b> Riddell, Danny, published by Pearson Education, Inc, publishing as Peachpit Press, Copyright © 2004. Ail rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording or by any information storage retrieval system, without permission from Pearson Education, Inc. RUSSIAN language edition published by DMK PRESS, Copyright © 2004.
Все права защищены. Любая часть этой книги не может быть воспроизведена в какой бы то ни было форме и какими бы то ни было средствами без письменного разрешения владельцев авторских прав. Материал, изложенный в данной книге, многократно проверен. Но, поскольку вероятность технических ошибок все равно существует, издательство не можег гарантировать абсолютную точность и правильность приводимых сведений. В связи с этим издательство не несет ответственности за возможные ошибки, связанные с использованием книги.
ISBN 0-321-21920-1 (англ.) ISBN 5-94074-255-6 (рус.)
Copyright @ Peachpit Press, 2004 © Издание на русском языке, перевод на русский язык, оформление. ДМК Пресс, 2004
(ОДШМ \ъ
Введение Глава 1. Основы Maya
17
О программе Maya
17
Системы координат в Maya
18
Интерфейс Maya
20
Использование Shelf Строка подсказки Редактор каналов
22 24 25
Редактор атрибутов
26
Меню Hotbox
27
Окно Hypergraph
29
Зависимости
31
Окно Outliner История создания Начало проекта
33 34 36
Импорт, экспорт и ссылки
39
Определение настроек Maya
43
«Горячие» клавиши
48
Справочная система Maya
49
Глава 2. Навигация по интерфейсу и настройка Откат, смещение и поворот камеры Настройка разметки интерфейса Меню Show .,
si 52 54 ... 63
6
Maya 5 для Windows и Macintosh Сглаживание и опции отображения «Горячие» клавиши для тонирования и сгпаживания Меню View
Глава 3. Создание примитивов и текстовых объектов
72 73 74
77
Кратко о NURBS
79
Примитивы NURBS
81
Создание примитивов NURBS Изменение атрибутов примитивов NURBS Атрибуты примитивов NURBS
82 86 88
Полигоны
90
Полигональные примитивы
91
Создание полигональных примитивов Изменение атрибутов полигонального примитива Атрибуты полигонального примитива Текстовые объекты
92 94 97 99
Присваивание названия объектам
103
Центры трансформаций
105
Глава 4. Режимы выделения, скрытие и шаблоны
ю?
Выбор объектов и использование Pick mask
109
Выделение объектов в режиме Hierarchy Выделение объектов в режиме Object Type Выделение частей объектов в режиме Component «Горячие» клавиши для инструмента Pick mask
112 114 116 118
Понятие о слоях
Глава 5. Преобразование объектов и компонентов Перемещение, вращение и масштабирование объектов Инструмент Show Manipulator Опции копирования Зеркальное отражение объектов и создание экземпляров
122
125 126 132 136 136
Содержание
Глава 6. Группирование, наследование и выравнивание
не
Группирование и наследование
150
Выравнивание и привязка объектов
156
Четыре вида привязки Инструменты группы Snap Align
158 162
Глава 7. Кривые и поверхности NURBS
ies
Объекты NURBS
169
Создание кривых NURBS
170
Анатомия кривой Создание кривых с различными степенями Создание профильных кривых Двумерные скругления Размыкание и замыкание кривых Создание поверхностей из кривых
Глава 8. Полигоны и поверхности разделения
171 173 174 177 179 181
192
Полигональное моделирование
194
Моделирование поверхностей разделения
220
Компоненты поверхности разделения Создание рельефа поверхностей разделения Полигональный режим поверхности разделения
Глава 9. Скелеты и обратная кинематика
221 223 227
235
Суставы 1К-манипуляторы и решатели
236 244
Сплайн обратной кинематики
249
Глава 10. Наследование и привязка к скелету Кластеры и вес Инструмент Attribute Paint Общие понятия о привязке
Глава 11. Анимация
гы. 255 258 261
п\
Средства управления анимацией
272
Ключевые кадры
274
7
8
Maya 5 для Windows и Macintosh Настройка параметров анимации
278
Импорт звуковых файлов
281
Окно Graph Editor
283
Типы касательных
284
Окно Dope Sheet
291
Ограничения Типы ограничений
294 ,
294
Отключение анимационных каналов
296
Создание снимков
297
Анимация вдоль пути
299
Редактор Trax Editor
300
Деформатор Blend Shape
306
Предварительный просмотр анимации
308
Глава 12. Деформаторы
зю
Нелинейные деформаторы Деформатор Bend Деформатор Flare Деформатор Sine Деформатор Wave Деформатор Squash Деформатор Twist
311
,
312 313 314 316 317 319
Деформатор Lattice
320
Деформаторы Wire и Sculpt
322
Скрытие, отображение и удаление деформаторов
326
Глава 13. Создание освещения
32?
Создание настроения Редактор Установки
328
Hypershade
330
визуализации
332
Источники света Подсветка Направленный источник света
334 ,
337 341
Содержание Точечный источник света Прожектор Объемный источник света
342 344 346
Вид из источника света
349
Привязывание источника света
350
Имитация теней
352
Создание теней
352
Глава 14. Тонировщики и материалы
зво
Управление текстурами и тонировщиками в редакторе Hypershade Использование Hypershade Понятие материалов Общие атрибуты материалов Текстурирование поверхностей NURBS Проекционные текстуры Инструмент 3D Paint Текстурирование полигонов Панель инструментов UV Texture Editor Атрибуты материалов в окне Channel Box Эффект «плавающих» текстур
Глава 15. Камеры и визуализация Камеры Анимация камеры Фокусное расстояние Плоскости изображения Визуализация
362 363 365 365 368 380 384 387 392 394 394
395 396 399 404 405 406
Визуализатор Software Renderer
411
Буфер аппаратной визуализации
414
Трассировка лучей
417
Интерактивная фотореалистичная визуализация
420
Визуализатор Hardware Renderer
422
Визуализатор Vector Renderer
424
Визуализатор Mental Ray
428
9
10 Maya 5 для Windows и Macintosh
Глава 16. Динамика
4зз
Частицы
436
Типы визуализации
439
Типы аппаратной визуализации Типы программной визуализации
440 442
Поля
443
Общие атрибуты полей
444
Столкновения
446
Динамика твердых тел
448
Динамика мягких тел
450
Эффекты
452
Редактор Dynamic Relationships Editor
457
Эффекты жидкости
458
Контейнеры Атрибуты контейнеров с жидкостью Примеры эффектов жидкости Имитация океана и тонировщик Ocean Пруды ,
Предметный указатель
,
458 462 462 464 467
4?о
УПИ КНИГУ И ПОЛУЧИ ДЕНЬГИ ОБРАТНО!* тоимость данной книги возмещается при записи на курсы Центра Компьютерного Обу1ения «Специалист» при МГТУ им. Н. Э. Баумана: • Работа в программе MAYA 5.0: базовый курс • Работа в системе 3ds max для начинающих (часть I) • Работа в системе 3ds max для совершенствующихся (часть II) • Работа в системе 3ds max для профессионалов (часть III) • Курс Discreet: Компьютерный дизайн и анимация в 3ds max • Курс Autodesk: Дизайн интерьера в программе Autodesk VIZ Возмещение стоимости производится только в день оплаты обучения при предъявлении данной книги и кассового чека на покупку. Возмещение производится в размере стоимости, указанной на чеке, но не более 450 руб. за книгу. Зачитывается стоимость 1 книги за 2 единовременно оплаченных курса. Спешите записаться! Срок действия программы до 30 июня 2004 г. Полные правила действия программы читайте на www.specialisi.ru Центр Компьютерного Обучения «Специалист» при МГТУ им. Н.Э.Баумана является ведущим учебным центром в России в области компьютерной графики, дизайна, проектирования и ЗО-моделирования. Высочайшее качество обучения подтверждается уникальным набором авторизации от таких ведущих компаний-производителей программного обеспечения, как Autodesk, Discreet, Graphisoft, Corel. Центр проводит авторское и фирменное обучение по Adobe Photoshop, Illustrator, Premiere, inDesign, Acrobat, CorelDRAW, QuarkXPress, Autodesk AutoCAD, Mechanical Desktcp, Arhitectural Desktop, Inventor Series, VIZ, Discreet 3ds max, Graphisoft ArchiCAD, Alias МЛУА. Центр Компьютерного Обучения «Специалист» при МГТУ им. Н. Э. Баумана - крупнейший в России учебный центр, авторизованный ведущими производителями программного обеспечения и мировыми лидерами IT-индустрии: Microsoft, Autodesk, Discreet, Graphisoft, Corel, CompTIA, Novell, Certified Internet Webmaster, Security Certified Program. Центр является первым в России авторизованным центром тестирования по международным программам сертификации пользователей Microsoft Office Specialist и ECDL. Центр предлагает комплексные программы подготовки самого разного уровня - от курсов для начинающих до сертифицированных курсов Microsoft. Основные направления подготовки специалистов: Ингернет- и web-технологии; сетевые технологии; программирование и базы данных; компьютерная графика, анимация, дизайн; проектирование и ЗО-моделирование; настройка и ремонт компьютеров; подготовка пользователей и офисные специальности. Более 130 сертифицированных преподавателей ежедневно ведут занятия в 60 компьютерных классах. За 12 лет в Центре Компьютерного Обучения прошли подготовку свыше 120000 слушателей по более чем 300 курсам из всех краёв, республик и областей Российской Федерации, а также из стран ближнего и дальнего зарубежья. Каждый месяц в Центре проходят обучение более 3 тысяч слушателей. Адрес: 105005, Москва, м. Бауманская, Госпитальный пер., д. 4/6, 2 этаж Телефон: (095) 232-3216, 263-6633 E-mail:
[email protected] Internet: www.spedalist.ru
Посвящается моей потрясающей жене Е-Цзюй (Yee-Ju) и моей семье. Они вдохновляли мой труд и верили в меня. Если бы не их любовь, преданность и поддержка, не было бы этой книги.
Благодарности Хочу поблагодарить Эндрю Бритта (Andrew Britt) за грамотный обзор первого издания; Ребекку Гулик (Rebecca Gulick) за ценные указания и помощь, которую она мне оказывала в процессе написания книги; Джуди Зьяжка (Judy Ziajka) за то, что направляла мои слова в нужное русло; Марджори Байер (Marjorie Ваег) за постоянную поддержку и руководство; Хайлала Сала (HHal Sala) и Джерри Болью (Jerry Ballew) за талантливую редактуру и дизайн; Эрика Андерсона (Eric Anderson) за исправления технического характера.
Рис. 1. Эта прожорливая доисторическая ящерица всего лишь одно из многочисленных существ, в которые вы можете вдохнуть жизнь с помощью Maya
AliaslWavefront Maya - это современная программа трехмерной графики (или просто ЗО-программа), давшая жизнь огромному количеству трехмерных персонажей: животным, растениям, машинам и механизмам, которые вы видите в фильмах, на видео и в играх. Что бы вы ни создавали - гонки на грузовиках, реалистичную анатомию или сцены художественного содержания, - Maya поможет достичь нужной формы и ощущения сцены. При работе с Maya все зависит только от вашей фантазии: Maya позволяет оживить любой придуманный вами персонаж, при этом полученным в результате объектом можно будет полностью управлять (рис. 1.1). Maya является чрезвычайно мощным приложением для создания анимации. В этой программе есть инструменты как для традиционной мультипликации, так и для создания фотореалистичных персонажей, поэтому из всех ЗО-программ профессионалы отдают предпочтение именно Maya. Данная книга познакомит вас с интерфейсом Maya и ее возможностями. Однако вы быстро поймете, что эта программа настолько глубока, что изучать ее можно годами. Пользователь, имеющий небольшой опыт работы с трехмерной графикой, достаточно быстро научится воплощать в Maya свои самые смелые
14
Maya 5 для Windows и Macintosh
фантазии, что делает программу чрезвычайно увлекательной. Для начинающих Maya проста в изучении, но профессионалы найдут в ней множество полезных и сложных функций, которые позволяют достичь настоящих вершин в создании ЗО-графики,
Читательская аудитория Если вы новичок, изучающий принципы создания трехмерной графики, или пользователь другого ЗО-приложения, желающий освоить Maya, эта книга для вас! Для эффективного освоения материала вы должны иметь навыки работы в графических приложениях, однако какой-либо опыт трехмерного моделирования не понадобится (хотя это помогло бы быстрее изучить Maya). Если вы внимательно прочитаете эту книгу и выполните все приведенные в ней примеры, вы совершенстве освоите интерфейс Maya, возможности предоставляемого программой инструментария, а также научитесь создавать трехмерные модели, сцены, подбирать нужный материал и текстуру и анимировать ЗО-объекты, Однако следует помнить, что данная книга является лишь хорошей основой для дальнейшего изучения программы. Для желающих продолжить восхождение к вершинам мастерства можно рекомендовать сайты www.upaxis.ru и www.carboncollege.ru, на которых вы найдете массу полезных ссылок и интересных примеров. Как правило, дизайнеры отдают предпочтение какому-либо определенному этапу работы над ЗО-проектом: моделированию, анимированию, настройке материалов и текстур, визуализации. Изучая рассмотренные в книге примеры, попробуйте определить, какой из этапов представляет
для вас наибольший интерес, а затем средоточьтесь на нем при создании ее ственной работы. И кто знает, мояк быть, вы сделаете карьеру в области со здания объектов ЗВ-графики для кино, рекламы или компьютерных игр, а может быть, Maya превратится для вас в новое хобби.
Требования к программному обеспечению Для работы над книгой необходимо установить на компьютер копию программы Maya для Windows или Macintosh. Инструкция по инсталляции программы содержится в документации Maya.
Версии программного пакета Maya В этой книге рассказывается о Maya 5 для Windows и Macintosh OS X (рис. 2-3). Разница между двумя версиями Maya 5 очень мала. Какие-ЛЕ:бо отличия в функциональности будут оговорены особо. Одно из различий между интерфейсом в Windows и Мае заключается в том, что в Мае можно С'тделить меню Hotbox. Другим отличием является то, что для W i n dows существует три версии Maya 5: Builder (облегченная). Complete (полная) и Unlimited (неограниченная), а для Mac OS X только одна, полная. Рассмотрим различные версии Maya для Windows более подробно: • Maya Builder (Облегченная). Эта версия предназначена для низкополигоналъного1 моделирования и разработки игр. В нее включен полный набор инструментов для полигонального моделирования, которь;;е используются для создания
Введение (is визуализируемых в реальном времени ЗО-объектов для Web и персонажей компьютерных игр; Maya Complete (Полная версия). Она включает в себя все инструменты и возможности Maya Builder, а также инструменты для сложной анимации объектов, имитации динамики (использование законов физики для моделирования реалистичного движения) и различные эффекты;
Рис. 2. Интерфейс Maya 5 в Windows [е • И Н **-"'* * Д.г •"Ks-K,j a^'Uf: bo\vit3\
»»*%•»»»•»»&. куатыи»***
Maya Unlimited (Неограниченная версия). Эта версия включает в себя все инструменты и функции Maya Complete, а также Maya Cloth (Одежда), Maya Fur (Мех), сложные инструменты для моделирования, Subdivison Surfaces (Поверхности разделения), Matchmovmg (Совмещение видео) и пакетную визуализацию Maya.
Рис. 3. Так выглядит интерфейс Maya 5 в Mac OS X
Polygon (англ.) - многоугольник. В профессиональном жаргоне ЗО-художникое установился термин «полигон» вместо «многоугольник». Низкополигональный - состоящий из небольшого числа многоугольников. - Прим. науч. ред.
16
Maya 5 для Windows и Macintosh
Данное издание предназначено для начинающих пользователей, поэтому здесь рассматриваются только инструменты и возможности полной версии Maya. Однако в книге представлена и динамика жидкости - новая функция, добавленная в версию Maya Unlimited 4.5 и недоступная в полной версии. Здесь не рассказывается о языке написания сценариев Maya, который называется MEL (Maya Embedded Language), так как это выходит за рамки книги, хотя этот язык используется во всех версиях программы.
Новое в Maya 5 Помимо того, что в версии 5 объединены версии Maya для Windows и Мае, в нее также включены дополнения к инструментам визуализации, например, Mental Ray, Vector Render (Векторный визуализатор) и Hardware Render (Аппаратный визуализатор). Новые расширенные возможности моделирования позволяют выдавливать полигоны вдоль пути и динамически уменьшать их количество. Об этих и многих других дополнительных функциях рассказывается в данной книге.
Дополнительные ресурсы В Internet существуют сотни ресурсов, посвященных Maya и 3D. Автор книги отдает предпочтение сайту www.upaxis.com. Этот ресурс содержит уроки и занятия, которые ежедневно обновляют и пополняют талантливые ЗВ-художники. Сайт UpAxis.com поддерживает онлайновая школа ЗО-анимации колледжа Carbon
college of Design (www.carboncoilege.con Рекомендуем также посетить сайты Hij hend 3D fwww.highend3d.com). 3D Caft twww.3dcafe.com) и Animation World Network fwww.awn.com), где вы получите подробные консультации по трехмерному моделированию и найдете массу полезной информации.
Принятые обозначения Полужирным шрифтом в тексте оформляются элементы интерфейса: названия окон, пунктов меню, команд, а также клавиш. Курсивом помечены базовые термины и определения. Web-адреса выделены подчеркиванием. В книге также используется несколько особых значков для привлечения внимания к определенным частям текста: Примечание. Этот значок предваряет дополнительную информацию, относящуюся к излагаемому материалу. Совет. Так помечены советы, которые помогут вам в практической работе. Внимание. Данный знак обращает ваше внимание на важные сведения, касающиеся функционирования программы Maya.
Полезная информация, которую следует иметь в виду при работе с программой, обведена рамочкой.
mm Рис. 1.1. Просмотреть узлы можно в окнах Hypergraph и Outliner. Для каждого объекта создается новый узел
1 Многослойный пользовательский интерфейс Maya в действительности очень прост в применении, так как позволяет быстро получить доступ ко всем функциям приложения. В этой главе вы познакомитесь с интерфейсом программы, научитесь изменять настройки, открывать проект и получать интерактивную помощь. Однако сначала нужно приобрести некоторое представление о том, как работает Maya.
О программе Maya
Рис. 1.2. Файл сцены в Maya обычно состоит из нескольких узлов и соединений, однако б более сложных сценах может содержаться около тысячи узлов
Основным понятием в Maya является узел. Узел — это наглядное представление элемента, например, поверхности, текстуры или анимационной кривой. Все элементы в программе отображаются одним узлом или несколькими связанными узлами (см. рис. 1.1). Узлы состоят из множества атрибутов, то есть качественной и количественной информации об узле, такой как положение объекта или его размер. Получить доступ к узлам позволяют панели Outliner (Планировщик) и Hypergraph (Гиперграф) - рис. 1.2. Их основное назначение
18
Основы Maya
одинаково - представить иерархическую схему (или план) конкретной сцены. Преимуществом подобной архитектуры является то, что вы можете в точности управлять всеми узлами, соединяя или разъединяя их, то есть определять вид и поведение объекта. Все соединения сцены можно просмотреть в окне Hypergraph (рис. 1.3), Линии со стрелками обозначают существующие соединения. (Более подробно об окне Hypergraph рассказывается далее.]
Системы координат в Maya Традиционные анимационные и графические приложения, например, Adobe Photoshop, работают с двумя осями, обычно это X и Y (рис. 1.4). В системе координат X и У есть высота и ширина, но нет глубины, изза которой объекты и становятся трехмерными. В Maya есть эта третья ось, ось Z (рис. 1.5). Добавление третьей оси позволяет создавать пропорционально точные модели.
Рис. 1.3. Соединения узлов можно /видеть на панели Hypergraph. Цветные линии со стрелками показывают соединения между узлами и их направление
Системы координат в Maya fl9 Системы координат XYZ делятся на два вида; глобальная (world) и локальная (local). Глобальные координаты начинаются в центре сцены в точке 0,0,0, которая называется началом координат (origin) рис. 1.6. Локальными называются координаты вокруг области объекта,
Рис. 1.4.20-графика работает с осями X и Y, поэтому в характеристиках объекта отсутствует глубина
Сами же объекты имеют 1ак называемое координатное пространство UV. У любой поверхности есть два направления: U и V. Для простой плоскости направление U идет слева направо, а направление V сверху вниз (рис. 1.7). Это аналог широты и долготы на карте мира. С помощью координат U и V можно задать положение точки на поверхности так же, как и с помощью широты и долготы определяется положение на географической карте. Это особенно важно при наложении текстур на поверхности,
Рис. 1.5. При добавлении еще одной оси объекты становятся трехмерными, что позволяет создавать очень правдоподобные модели
Рис. 1.7. Любая поверхность описывается с помощью направлений U и V. Они позволяют размещать кривые на поверхности
Рис. 1.6. Центральная точка сцены называется началом координат. Все значения направлений отсчитываются от нуля в начале координат
20
Основы Maya
Интерфейс Maya На первый взгляд интерфейс Maya выглядит довольно сложным, однако, изучив его, вы поймете, что это хорошо организованная и простая в обращении система (рис. L.8). В верхней части окна программы находится строка главного меню (main menu bar), которая содержит все основные команды. В Maya гораздо больше меню, чем может поместиться в окне, поэтому просматривать их все сразу в строке меню невозможно. По этой причине команды собраны в группы меню по задачам, к которым можно получить доступ, выбрав нужную группу из выпадающего списка слева от строки состояния. В строке состояния (status line), которая находится непосредственно под строкой главного меню, содержится большинство функций управления. Под строкой состояния расположена панель Shelf (Полка),
в которой находится часто используемы инструменты. В левой части главного окна расположена панель инструментов (toolbar), в которой содержатся инструменты управления объектами и видами в Maya. С их помощью можно выделять, поворачивать, перемещать объекты, а также изменять размеры объектов или их частей, которые называются компонентами. По умолчанию в Maya при открытии файла отображаются четыре вида: вид спереди (Front), вид сбоку (Side), вид сверху (Тор) и вид в перспективе (Perspective). Области экрана, содержащие эти виды, называются окнами вида, или окнами проекций (panes), По умолчанию сцена открывается в четырех окнах проекций. В нижней части главного окна расположены ползунок диапазона (Range Slider) я ползунок времени (Time Slider), с помощью которых можно управлять положением сцены во времени при создании анимации. С правой стороны
Рис. 1.8. На рисунке представлен интерфейс Maya, установленный по умэлчанию. Большлнство элементов, которые здесь отображены, можно скрыть или привязать к текущей задаче
Интерфейс Maya
21
главного окна находится редактор каналов (Channel Box), в котором содержатся числовые поля атрибутов объектов.
Рис. 1.9. Контекстное меню предоставляет быстрый доступ к командам редактирования различных компонентов
Рис. 1.10. Конфигурация элементов инструмента Hotbox, принятая по умолчанию. Состав отображаемых команд можно изменить в меню Hotbox Controls
Доступ к командам можно получить не только с помощью строки главного меню, но и воспользовавшись отдельными панелями или контекстным меню (Marking Menu) - рис. 1.9. Эти меню позволяют быстро активизировать нужный инструмент или выполнить команду. Контекстное меню можно вызвать, щелкнув по объекту правой кнопкой мыши или щелкнув по одной из пяти областей быстрого меню Hotbox (см. далее раздел «Меню Hotbox»). В Maya очень много различных меню, поэтому потребуется достаточно много Etpeмени, чтобы освоить все содержащиеся в них команды. Инструмент оперативного доступа к элементам пользовательского интерфейса Hotbox (Быстрое меню) позволяет вывести на экран все необходимые меню в тот или иной момент работы (рис. 1.10). Если вы нажмете клавишу пробела, то быстрое меню появится на экране прямо под указателем мыши (и исчезнет, если клавишу отпустить). Hotbox позволяет значительно сэкономить время, так как получить доступ к нему можно при любом положении указателя мыши, не перемещаясь в строку главного меню, чтобы выбрать команду,
22 Основы Maya Чтобы изменить положение объекта, повернуть его или промасштабировать {все вместе это называется преобразованиями), нужно ввести соответствующие значения в редакторе каналов (рис, 1.11) или воспользоваться манипуляторами Maya, с помощью которых можно изменять значения атрибутов объекта, щелкнув по маркеру и перетащив его мышью в другое положение (рис. 1.12).
Channels Object
niirbeConel Translate X i Translate Y ' Translate Z ' Rotate X о Rotate V .0
Рис. 1.11. Можно изменять значения атрибутов следующим образом: выделите имя атрибута и перемещайте указатель мыши в окне вида, удерживая нажатой среднюю кнопку мыши
Использование Shelf На полке (Shelf) хранятся часто используемые инструменты и команды. Чтобы собрать наиболее применяемые инструменты, можно воспользоваться обширным набором предварительно заданных полок, предоставляемым Maya 5 (рис. 1.13). На рис. 1.13 изображены все устанавливаемые по умолчанию полки: General (Общие), Curves (Кривые), Surfaces (Поверхности), Polygons (Многоугольники), Subdivs (Поверхности разделения), Deformation (Деформации), Animation (Анимация), Dynamics (Динамика), Rendering (Визуализация), Paint Effects (Рисование), Cloth (Одежда), Fluids (Жидкости), Fur (Мех). Добавлять элементы в отдельные наборы полок очень удобно. Например,
Рис. 1.12. Этот конус окружен манипулятором вращения. Объект мэжно повернуть, выделив окружности и переместив их
Рис. 1.13. В полках собраны инструменты и команды. Вы можете изменять их или создавато для текущей задачи дополнительные полки с часто используемыми командами и инструментами
Использование Shelf jlay
Window
Etit Curves
Surface;
Grid Heads Up Display
Э *
Рис. 1.14. Множество отображаемых окон и панелей уменьшает рабочее пространство. Громоздкие элементы можно скрыть, убрав галочку в подменю Display => Ul Elements
23
можно создать одну полку для инструментов моделирования, а другую - для инструментов визуализации. Можно сформировать и третью полку с десятью или пятнадцатью часто используемыми инструментами и командами. Допускается добавлять в полку элементы или удалять их, а также использовать любую заранее установленную в полке команду. Несмотря на всю приносимую пользу полка иногда метает работе, поскольку занимает много места на экране. Если нужно освободить рабочее пространство, полку можно скрыть. Чтобы скрыть полку, выполните команды меню Display =>UI Elements => Shelf (Показ ^> Элементы интерфейса пользователя ^ Полка) - рис. 1.14, Элементы, помещаемые в полку, сохраняют последние установки, а это значит, что можно добавить один и тот же инструмент дважды, но с различными установками. Например, попробуйте добавить в полку две иконки, заменяющие команды Create => Primitive "=> Sphere (Создать => Примитив "=> Сфера}, но одна сфера будет занимать 360°, а другая меньше 360° (например, 240). Чтобы создать сферу с нужным числом градусов, не возвращаясь к настройкам, вы можете просто щелкнуть по любой из этих иконок.
Добавление объекта на полку С одновременным нажатием клавиш Ctrl/ Control и Shift выберите тот элемент меню, который требуется добавить на полку. На полке появится нужный инструмент.
Удаление объекта с полки Чтобы удалить инструмент, с помощью средней кнопки мыши перетащите его с полки в корзину.
24
Основы Maya
Строка подсказки
View Shadng Lign:ing_5ho^_ P tk Selection
В строке подсказки (Help Line) отображается информация о преобразованиях объекта, а также сведения о том, каков должен быть ваш следующий шаг. Когда вы проводите указателем мыши над элементом меню, в строке подсказки появляется описание шагов, которые нужно предпринять, чтобы завершить команду. Если вы поворачиваете объект, изменения отобразятся в строке подсказки в виде чисел (рис. 1.15). Точные значения преобразований можно ввести в поле Numeric Input (Ввод численных данных), которое находится слева от строки состояния. Это необходимо, если требуется точно определить положение объектов, таких как части архитектурных сооружений или различных механизмов. Maya предоставляет возможность выбора: выполнять построения на глаз или вводить точные цифры, определяющие положение и размер объектов. После внесения изменений в строке подсказки появляются новые значения.
ick Re папе .merit Input: Relativ
-
I
I
10 I
15 I
20 I
Z5 I
и I
Rolation[degj: 0.000
Рис. 1.15. В строке подсказки отображается важная информация о командах и преобразованиях объектов. В нижней части рисунка в градусах представлено значение поворота сферы
!
Редактор каналов
25
Редактор каналов
Рис. 1.16. В редакторе каналов содержится вся информация об объекте: в строках Translate описывается его положение, в строках Scale изменение размеров, Rotate - поворот. Это составляющие узла преобразований Translate ХИО.ЭБЭ Translate V 3.526 Translate 2|Rotate X:Q Йо!а!е Rot at e Z P Scale Х1Ш83 JB3 Scale 11ШВЭ Visibility ion
Рис. 1.17. По умолчанию ключевыми считаются десять атрибутов объекта, но вы можете добавлять атрибуты или удалять их из списка
Редактор каналов {Channel Box), в котором перечислены ключевые атрибуты объекта, расположен в правой части главного окна Maya (рис. 1.16J. Ключевыми атрибутами называются основные свойства объекта, использующиеся при анимации. Редактор каналов позволяет быстро изменить значение атрибута, не открывая еще одно лишнее окно {таким образом экономится рабочее пространство). Чтобы переопределить значение атрибута, в его поле следует ввести нужное число или же щелкнуть по имени атрибута и переместить указатель мыши в любом окне проекции, удерживая нажатой среднюю кнопку мыши. При выделении объекта в редакторе каналов отобразятся его атрибуты, устанавливаемые по умолчанию (рис. 1.17): Translate X (Перемещение по X), Translate Y (Перемещение по Y), Translate Z (Перемещение по Z), Rotate X (Поворот относительно X), Rotate Y (Поворот относительно Y), Rotate Z (Поворот относительно Z), Scale X (Изменить размер по X), Scale Y (Изменить размер по Y), Scale Z {Изменить размер по Z) и Visibility (Видимость). Значения для этих атрибутов можно вводить по одному, в небольших наборах или все сразу. С помощью окна Channel Control [Управление каналами) список атрибутов редактора каналов можно дополнить, сделав ключевыми другие атрибуты объекта.
26
Основы Maya
Под узлом преобразований расположены узлы Shapes (Формы) и Inputs (Входные данные) - рис. 1.18. В разделе Shapes перечислены названия каждого объекта. Эти узлы определяют геометрию объекта. Например, при создании сферы в разделе Shapes появляется элемент pSphereShape. Если объект состоит из нескольких форм, их узлы также перечисляются в данном разделе. В разделе Inputs обычно находятся атрибуты, влияющие на историю создания выбранного объекта (см. далее раздел «История создания»). При выделении нескольких объектов в редакторе каналов отображается последний выбранный объект; однако любое изменение значений атрибута отразится на всех выделенных объектах. Чтобы выделить несколько значений в редакторе каналов, нужно выбрать их, удерживая нажатой клавишу Ctrl/Control (рис. 1.19). Теперь изменение одного из них отразится на значениях всех выделенных атрибутов.
SHAPES пм beSpher eShape 1 INPUTS makeHUrtlSpherel Ratiui I Start Sweep id
Рис. 1.18. Чтобы изменить свойства поверхности после ее создания, переопределите атрибуты узла Inputs
- V
' 1
nurbsSpherel Translate К jo Transiele V Translate Z Rotate X RcteleYlQ Rotate Z Scale Э Scale I 1 VISlbHtv 'oi
Рис. 1.19. Если в редакторе каналов выделено несколько атрибутов, их можно изменять одновременно
j иЬаВЬаАаВюЛ! '!
TumttnmAtllfeutet
Редактор атрибутов Редактор атрибутов (Attribute Editor) похож на редактор каналов, поскольку позволяет работать с атрибутами объекта. Однако редактор атрибутов открывает доступ ко всем атрибутам объекта, а редактор каналов - только к тем, которые могут стать ключевыми в анимации (рис. 1.20). Еще одно отличие заключается в том, что в Attribute Editor находятся атрибуты, на которые нельзя назначить ключевые кадры (то есть нельзя использовать при создании анимации), а следовательно, нельзя переместить в редактор каналов.
_>, liniMnlniMiiini Jj Ditpla» * Nii.lt BehavMt tfltfiAllnbulei
Select
Lrad А
Рис. 1.20. В редакторе атрибутов содержится вся информация о выделенном объекте
Меню Hotbox
27
Меню Hotbox
Рис. 1.21. Для каждой из областей быстрого меню - North, South, East, West и Center - есть соответствующее контекстное меню. Центральная область определяется символом A/W
Меню Hotbox {Быстрое меню) содержит наборы меню, к которым можно получить доступ простым нажатием и удерживанием клавиши Пробел при любом положении указателя мыши. Быстрое меню разделено на пять областей: North (Северная), South (Южная), East (Восточная), West (Западная) и Center (Центральная) - рис. 1.21, У каждой области есть соответствующее ей контекстное меню {Marking Menu). По умолчанию в контекстном меню для северной области содержатся ярлыки для различной компоновки элементов интерфейса (например, Single Perspective (Только перспектива)) - рис. 1.22. В южной области переопределяется содержимое активного рабочего окна (рис. 1.23), например, вид Perspective меняется на Outliner (см. ниже раздел «Окно Outliner»}. В меню западной области находятся заранее заданные маски выбора (рис. 1.24), с помощью которых фильтруются те или иные объекты. Меню восточной области позволяет скрыть или отобразить отдельные
Рис. 1.22. В контекстном меню северной области можно выбрать различные схемы интерфейса
File
Edit **
View
Animat*
Modify
e
Display
- — ^ • • ^ ^ ^ ^ ^ ^ • « • i
Shading
Deform
lighting
Skeleton
Skin
Show
Panels
Constrain
Character
. • • • Stl Eflllal Graph Dlitc
h• .• • •
Рис. 1.23. С помощью контекстного меню южной области можно менять содержимое панелей
Рис. 1.24. В контекстном меню западной области можно изменять режимы выбора объектов и компонентов
28 Основы Maya элементы пользовательского интерфейса [рис. 1.25). Например, с его помощью можно скрыть полку и освободить пространство. Меню центральной области содержит ярлыки для переключения между панелями видов (например, с вида спереди на перспективу) - рис. 1.26, Помимо контекстных меню, Hotbox предоставляет доступ ко всем наборам меню Maya. В верхней строке всегда находятся такие основные меню (имеющиеся во всех режимах), как Window (Окно) или Create (Создать). Во второй строке дублируется меню активного окна. Третья строка включает меню Recent Commands (Последние команды), при помощи которого можно просмотреть 15 последних исполненных команд, и меню Hotbox Controls (Элементы Hotbox), позволяющее настроить режим отображения информации в меню Hotbox.
Рис. 1.25. Контекстное меню восточной области позволяет скрыть/отобразить элементы интерфейса
Рис. 1.26. С помошью меню центральной области можно быстро переключаться между видами
Hotbox Controls позволяет скрыть или показать элементы меню Hotbox. На экране можно оставить только среднюю строку, сделать видимым другой набор меню или отобразить все строки одновременно (рис. 1.27).
Отображение всех наборов меню в Hotbox 1. Нажмите и удерживайте клавишу Пробел. Меню Hotbox будет отображаться на экране, пока вы не отпустите эту клавишу.
Рис. 1.27. В данном случае отображены все компоненты меню Hotbox
2. Щелкните но кнопке Hotbox Controls, На экране появится контекстное меню (рис. 1.28).
Рис. 1.28. Меню Hotbox позволяет просматривать как один набор меню, так и все меню программы
Окно Hypergraph 3. Удерживая клавишу Пробел и кнопку мыши, выберите пункт Show All (Отобразить все). Как только вы отпустите кнопку мыши, на экране появятся все наборы меню (рис. 1.27). Такое отображение позволяет быстро найти любое меню программы, не тратя время на долгий поиск.
Окно Hypergraph Рис. 1.29. Иерархическая структура состоит из узлов, соединенных между собой. Эти связи отображаются в окнах Hypergraph и Outliner
Рис. 1.30. Маленький значок на каждом узле обозначает тип объекта этого узла. Например, у узла поверхности {левый столбец) рядом с названием есть маленький синий значок, напоминающий простую поверхность
Окно Hypergraph (Гиперграф} содержит представление сцены с использованием элементов, подобных гипертекстовым (отсюда и его название). Если вам когда-нибудь приходилось работать с HTML Authoring tool, БЫ сразу заметите, что объекты в окне Hypergraph имеют Web-вид. Hypergraph показывает, как организованы и соединены все узлы в сцене. От этих соединений зависит качество конечной анимации и визуализации. Создание персонажей и их перемещение невозможны без правильного соединения узлов, иначе части тела персонажей двигались бы неестественным образом, не составляя единого целого. Такая организация и соединение отдельных узлов называется иерархией (рис. 1.29). Иерархия сцены отображается в окнах Hypergraph и Outliner, ее можно настраивать, то есть добавлять и удалять связи мел-еду элементами сцены. Для каждого типа объекта в Maya есть соответствующий значок (рис. 1.30). Без тпких значков ярлыки всех объектов выглядели бы совершенно одинаково. По мере знакомства с программой пы начнете узнавать значок каждого типа объекта. Так, например, выглядит значок кривой - j£;, а так V^ - значок объекта Spotlight. В окне Hypergraph можно просматривать узлы по
30
Основы Maya
типу объекта (рис. 1.31) или же отображать все узлы сразу (рис. 1.32). Узлы, не участвующие в анимации, представлены в виде прямоугольника, а узлы, задействованные в ключевых кадрах, - в виде параллелограмма (рис. 1.33).
Рис. 1.31. Чтобы упростить поиск и выбор объектов, в окне Hypergraph можно отобразить узлы одного типа объектов. Например, для моделирования, зозможно, понадобятся только кривые и поверхности. А для анимирования потребуются тол эко соединения и IK-указатели, использующиеся для выбора и перемещения частей персонажа и имитирующие движение
Рис. 1.32. По умолчанию для окна Hypergraph установлена опцич Show All. Этот вид помогает проиллюстрировать, как геометрия связана с узлом, а также предоставляет другую информацию об иерархии
Зависимости
31
Зависимости
Рис. 1.33. Узлы, задействованные в ключевых кадрах, представлены в виде параллелограммов, что позволяет предотвратить нежелательные анимации объекта
Рис. 1.34. Исходящий и входящий граф объекта показывает соединения с другими объектами, Некоторые из этих зависимостей могут соответствовать группам объектов, источникам света или текстуре
Рис. 1.35. Чтобы освободить место в окне Hypergraph, иерархию можно свернуть. Свернутая иерархия обозначается красной стрелкой, расположенной под верхним узлом
Каждый узел в окне Hypergraph имеет зависимости (dependences), которые соединяют его с другими узлами. Например, вы выделили вновь созданную сферу, чтобы рассмотреть ее исходящие и входящие соединения в Hypergraph (рис. 1.34). На экране отобразятся узел Shape сферы, узел Shader, устанавливаемый по умолчанию, и соединенный с ним узел makeNurbs Construction History. Стрелки между узлами показывают направление соединений. Один из способов увидеть все взаимосвязи узла нажать па кнопку Show Upstream and Downstream Connections (Показать исходящие и входящие соединения) «£. Закончив просмотр данных соединений, нажмите на кнопку Scene Hierarchy (Иерархия сцены) ^, чтобы в Hypergraph вновь появилась общая иерархия сцены. Чтобы сократить число узлов, отображаемых на экране, дочерние узлы можно свернуть. На родительском узле при этом появится красная стрелка (рис. 1.35). Чтобы свернуть иерархию, дважды щелкните по верхнему узлу. Двойной щелчок по
32
Основы Maya
верхнему узлу свернутой иерархии разворачивает ее по одному узлу за один pan [рис. 1.36). Чтобы развернуть всю иерархию, щелкните правой кнопкой мыши по самому верхнему узлу и выберите в выпадающем меню пункт Expand All (Развернуть все) - рис. 1.37. Благодаря тому, что Hypergraph обеспечивает доступ ко многим данным, он быстро завоевывает симпатии пользователей. Этот инструмент позволяет поддерживать функциональность и организованность сцены, поскольку с его помощью можно соединить, разъединять и перемещать узлы, на которых построена работа программы.
Рис. 1.36. Иерархии можно развернуть, чтобы посмотреть, какие узлы являются дочерними, после чего вновь свернуть, чтобы не загромождать окно Hypergraph
Рис. 1.37. Если вы захотите увидеть иерархию целиком, щелкните правой кнопкой мыши по верхнему узлу и выберите пункт Expand All
Зависимости
33
Окно Outliner Display .. I j.
p '
Fi
ill-
£J
rfoolc
£?
ballNull
jf
nurbsSpherel
Jf
nghiLeg
]H[ ftdl Lattice g fid! Base
ш
£7
rfoolc1
£7
ballNulll
^' nuibSpheie2 ^/
righlLeg!
tH HdUatlicel
PHU 1.38. СПИСОК
Outliner появляется в небольшом окне, что упрощает промесс выбора и перемещения объектов
Рис. 1.39. Окно Outliner, как и Hypergraph. позволяет скрывать и отображать объекты
В окне Outliner {Планировщик} представлена общая схема сцены, что делает его похожим на Hypergraph. Иерархия отображается в виде списка (рис. 1.38), что упрощает поиск объектов и их выбор. В меню Outliner содержатся команды фильтрации конкретных типов объектов, позволяющие сократить количество отображаемых в списке узлов (рис. 1.39). В окне Outliner можно изменять положение объекта в иерархии и быстро выбирать объекты, которые находятся на самых глубоких уровнях иерархии. Если окно Outliner открыто, а в сцене еще не создано ни одного объекта, то помимо значков defaultLightSet и defaultObjectSet вы увидите цветные значки видов сверху, спереди, сбоку и в перспективе (обратите внимание, что все ортогональные виды здесь считаются камерами) рис. 1.40. По мере создания каждого нового объекта в списке отображается новый узел. Если установлены соединения и построена иерархия, то рядом с родительским объектом иерархии появляется плюс, нажатие на который раскрывает список дочерних объектов (рис. 1.41).
Display Show Help
"•*! •**' pEfSp top
Itont side
С) G
ЗЭ-81
delaullLightSel deMtGbjeclSel
Рис. 1.40. Новая сцена в Outliner содержит четыре камеры видов, которые устанавливаются по умолчанию
Рис. 1.41. Чтобы увидеть дочерние объекты, щелкните по плюсу и раскройте иерархию. У каждого объекта в Outliner есть свой значок, обозначающий его тип
34
Основы Maya
У окна OutHner небольшие размеры, что делает его удобным инструментом для выбора объектов. Однако инструмент Hypergraph предоставляет большую гибкость в управлении узлами. Если для простых сцен вполне годится инструмент Outliner, то для сложных лучше использовать Нуpergraph, с более совершенным интерфейсом, позволяющим просматривать сотни элементов.
История создания По мере построения объектов Maya сохраняет связи с первоначальными кривыми или поверхностями, которые использовались при моделировании. Эта связь называется историей создания (construction history). Поскольку в истории создания записаны шаги, которые вы совершали при моделировании объекта, его конечную форму можно изменить, переопределив начальную кривую или поверхность. Это позволяет изменить поверхность, не создавая ее заново. В качестве примера рассмотрим рисование кривой, которая определяет форму вазы (рис. 1.42), и ее последующее вращение вокруг вертикальной оси, в результате которого очерчивается полный контур объекта (рис. 1.43). В истории создания записывается положение кривой, которое привязывается к форме конечной поверхности. Чтобы изменить форму вазы,
Рис. 1.42. Кривые используются для создания контура формы - при вращении вокруг какой-либо оси они моделируют поверхность
Рис. 1.43. На осноие одной и той же кривой можно создать бесчисленное количество объектов, с помощью истории создания изменяя конечную форму поверхности уже после того, как поверхность Еыла построена
Зависимости 35 нужно выбрать часть начальной кривой и переместить ее; в результате поверхность изменится в соответствии с изменениями кривой (рис. 1.44),
Рис. 1.44. Чтобы изменить форму поверхности, нужно выделить и переместить целую кривую или ее отдельные точки. В истории создания узел поверхности присоединен к узлу кривой, поэтому поверхность повторяет изменения этой кривой HJPUT8 Radius
Degree Sections
Рис. 1.45. Поверхность примитива можно изменить с помощью его узла Inputs, содержащего многочисленные атрибуты, которые используются при редактировании. Каждый тип объекта имеет уникальные атрибуты
У большинства примитивов NURBS (NonUniform Rational B-Spline - неоднородные рациональные би-сплайны) и полигональных объектов есть история создания, которая присоединена к узлам поверхностей. Узлы History для примитивов находятся в Channel Box под заголовком Inputs и используются для изменения основных атрибутов объекта после его создания. В качестве примера рассмотрим изменение конечной точки развертки сферы, в результате чего из формы вырезается кусок (рис. 1.45).
Включение и отключение истории создания В строке состояния щелкните по кнопке Construction History On/Off. Пиктограм ма 3$ на данной кнопке означает, что история включена, а $ - отключена. Отключение этой функции для всей сцены или отдельного объекта позволяет увеличить скорость работы, но значительно снижает ее гибкость, поскольку история создания предоставляет дополнительные средства контроля и больше свободы для реализации альтернативных возможностей моделирования. Если история создания отключена, она не войдет ни в один из создаваемых объектов. Чтобы добавить историю создания, нужно перестроить объект.
36
Основы Maya
Удаление истории создания объекта \ШЛ
1. Чтобы создать сферу, в меню Create (Создать) выберите пункты NURBS Primitive => Sphere (Примитив NURBS => Сфера) или выделите объект.
ЧН
Bitt
v«w
•
Со три: и
Images
•ii
lends rDiU
2. В меню Edit (Редактирование) выберите пункты Delete by Type "=> History (Удалить по типу => История).
Создав новый проект, необходимо определить его в качестве рабочего. Если проект определен, Maya автоматически размещает файлы по папкам, точно зная, например, в какие папки поместить визуализированные изображения, а в какие сцены. Рабочий файл Maya, называемый файлом сцены (scene file), следует хранить в папке Scenes. Лучший способ организовать хорошую файловую структуру - создать новый проект, определить его, создать новую сцену и сохранить ее в папке Scenes. В следующем разделе создание проекта описывается по шагам.
Создание нового проекта 1. В меню File (Файл) выберите команды Project ^> New (Проект ^ Создать) рис. 1.47.
render$c*nts
workspace, mil
Начало проекта Для каждого проекта Maya может создаваться огромное количество файлов, поэтому для работы необходим набор папок, в котором несколько директорий будут отведены для хранения определенных типов файлов. Чтобы быстро систематизировать создаваемые файлы, можно использовать предоставляемые Maya готовые наборы папок, которые называются проектами (project) - рис. 1.46,
Нате fivoni* Create Reference лп1т|идян»тада!.
то"Н "5'fWaД'Г
] :hark_expcrt
3. Выделите этот файл и нажмите кнопку Reference (рис. 1.62). Теперь в сцене есть объекты со ссылкой на файл.
Определение настроек Maya В Maya есть множество настроек (preferences), изменяя которые можно подобрать оптимальный для вас стиль работы с интерфейсом и наиболее подходящую цветовую схему. В этом разделе рассказывается только о нескольких наиболее важных настройках (более подробную информацию о различных настройках вы найдете в файлах помощи Maya). Программа позволяет устанавливать количество разрешенных отмен действий (undo), которые определяют, сколько раз можно отменить предыдущие команды.
Рис. 1.62. Укажите путь к файлу, на который будут ссылаться остальные файлы, и нажмите кнопку Reference или дважды щелкните по имени файла
44
Основы Maya
Изменение количества отмен
Wmdow
PWdcies
1. В меню Window (Окно) выберите пункт Settings/Preferences => Preferences (Установки/настройки => Настройки) рис. 1.63. Откроется окно Preferences. 2. Чтобы просмотреть свойства команды Undo, щелкните по пункту Undo (Отменить) в списке под заголовком Gategories (Категории) - рис. 1.64. Откроется раздел Undo.
Мпвтиге Application Raise Mam Window Rase Applcation Windows
Рис. 1.63. Определенные вами настэойки будут приняты по умолчанию, поэтому каждый раз при запуске программа открывается с нужной вам конфигурацией интерфейса
Jdit _ Help Categotiai ntaface UI Element! Muc Display Kinematics Animation Msmpuiatois NURBS Polygons Settings Dynamics Ftes/Proiects Ke>s Modeling Selectior Snapping be i «id Timeline
Рис. 1.64. Чтобы изменить число разрешенных отмен действий, в окне Preferences выберите пункт Undo
Определение настроек Maya 45 Pr* fed nets Нив а»90П#ь F.iss/Proje
>•, Wazrlma
Undo: Undo Queue Settings .
undo
—
———
-~~~
Undo За, Sphere. В начале координат будет создана сфера. 2. Выберите инструмент Move, нажав на клавишу w или на кнопку Move на панели инструментов ф. Рис. 1.67. Не закрывая окно Preferences, выделите сферу щелчком мыши
3. В меню Window (Окно) выберите пункты Settings/Preferences ^> Preferences (Установки/настройки => Настройки). Откроется окно Preferences. 4. В списке категорий выберите пункт Manipulators (рис. 1.66). Справа отобразятся свойства манипулятора. 5. Переместите окно Preferences так, чтобы было видно сферу. Щелкните по сфере, чтобы убедиться в том, что она выделена (рис. 1.67).
46
Основы Maya
6. В разделе Manipulator Display Preferences медленно перемещайте ползунок Global Scale (Общий размер), пока не подберете нужный вам размер манипулятора (рис. 1.68). Передвигая ползунок, наблюдайте, как изменяются размеры манипулятора {рис. 1.69). 7. Переместите ползунок Handle Size (Размер меток) - рис. 1.70. Метка манипулятора (в данном случае стрелки) уменьшается при движении ползунка влево и увеличивается при перемещении вправо (рис. 1.71).
Рис. 168. Переопределяя числовое значение в поле Global Scale, можно поменять размеры манипуляторов. В данном случае они были уменьшены
Рис. 1,69. При перемещении ползунка вправо манипулятор увеличивается, при перемещении влево - уменьшается
Рис. 1.70. В числовом поле Handle Size определяются размеры метки манипулятора
Рис. 1.71. Значки метки манипулятора уменьшаются при перемещении ползунка влево и увеличиваются при перемещении вправо
Определение настроек Maya 47 Jaixl atari: ManipulalDi Diiplay Preleiencn Sum
Если вы по какой-то причине захотите вернуться к установкам по умолчанию, в окне Preferences выполните команды меню Edit => Restore Default Settings (рис. 1.72). Таким образом вы восстановите настройки, которые определяются по умолчанию.
Global Scale (ГИГ Handle Sue 'lOO
•
Slats Si» Mo" Shun Maniuutator Defsu» Manipulah* I Smart
•
M
При восстановлении установок, определенных по умолчанию, не забудьте в настройках отмены действий установить значение Infinite.
l
Рис. 1.72. В окне Preferences выполните команды меню Edit ц> Restore Default Settings, чтобы вернуться к первоначальным установкам
Изменение цветовой схемы Maya 1. В меню Window (Окно) выберите пункт Settings/Preferences c> Colors (Настройки/свойства с> Цвета) - рис. 1.73. Откроется окно Colors,
Animate Defurm Skeleton Ssneral SJIef! RernJeringSfiors Animation Editors RelaCiOnship Editor; Preference*... Ted Settings.™ PerfcrmafKKSettotgs...
AttrifMKe Editor..,
Возвращение к установкам по умолчанию
Hofteys... Paint Effects... UVTextae editor,
View ArrsTgement
2. Нажмите на стрелку рядом с надписр.ю 3D Views _т]зо¥ки*ш . чтобы отобразить ползунок, с помощью которого изменяется цвет фона (рис. 1.74).
Edit Hr-r,
youts
Genera! Active } Inaetrve] Frane All in All Views
A
Frame Selection Ш И! Views F Raise Me*l Windw Rai?e AprJr.ation Window:
tj Headi Up Ditplaf jj Annabon
Рис. 1.73. В окне Colors можно изменить цвета элементов интерфейса
jj Annation t dilori ^|J Hjipaiipaph •J Dulknci (Also dffeclt Aninatian and Relalionthi|i Edttwij Jj Tr«e Edttn
I Рис. 1.74. Чтобы открыть палитру Color Chooser, в окне Colors щелкните по образцу цвета рядом с надписью Background
48 Основы Maya 3. Чтобы открыть окно Color Chooser (Выбор цвета), щелкните по образцу цвета рядом с надписью Background (Фон). 4. В разделе Wheel (Цветовой круг) выберите тот цвет, которым вы хотите закрасить фон окон видов в Maya (рис. 1.75). 5. Нажмите кнопку Accept, чтобы применить настройки. Теперь в качестве фона будет использоваться выбранный вами цвет. Таким же образом вы можете изменить любую часть цветовой схемы интерфейса.
«Горячие» клавиши У любой функции в Maya есть сокращен* ный клавиатурный набор или «горячая» клавиша (hotkey). Горячие клавиши позволяют значительно сэкономить время, поскольку используются вместо выбора инструмента или команды в меню. По умолчанию в Maya установлено множество «горячих» клавиш, которые не рекомендуется переопределять до тех пор, пока вы не познакомитесь с интерфейсом достаточно подробно. Позднее вы, возможно, захотите создать «горячие» клавиши для определенных команд, которые используются регулярно. Давайте рассмотрим, как создать новую «горячую» клавишу или открыть список уже существующих.
Рис. 1.75. Чтобы выбрать цвет фона, щелкните в поле Wheel • Window
ftninala
Deform
Skeleton
General Edtnrs
>
Pandering Eifitors
*
ArtmabOT Editor?
*
Preferences.., Tool Settings.. Performance
Cokes, Marhng Mem Playblast,.
Shelves... Panels.,.
Saved Layouts Save Current Layeut . . Frame ftl in AS Views ft Frame Selection In All Vie^s F Minimise Application •
Создание «горячей» клавиши 1. В меню Window (Окно) выберите пункт Settings/Preferences ^ Hotkeys (Установки/свойства ^> Горячие клавиши) - см. рис. 1.76. Откроется окно Hotkey Editor (Редактор «горячих» клавиш).
R«se Application Whdow:;
Рис. 1.76. Практически любой команде или инструменту можно назначить сокращенный клавиатурный набор
Справочная система Maya
49
2. В окне Categories щелкните по названию категории команды, для которой требуется клавиатурное сокращение (рис. 1.77). Название категории совпадает с названием меню, в котором находится команда, 3. В меню Commands выберите название команды, для которой требуется создать «горячую» клавишу. Если у этой команды уже была соответствующая клавиатурная комбинация, вы увидите ее в правом верхнем углу окна в поле Current Hotkeys.
Рис. 1.77. Выберите в окне Hotkey Editor в списке категорий и команд название меню, в котором находится команда, и саму команду
Чей Hotkey
Kty I Modifier
!
Рис. 1.78 В разделе Assign New Hotkey выберите клавишу и модификатор клавишу Ctrl
или Alt
С enter ts anct Search Inde* Learning Movies Tutorials Maya Support Solutions AhaslWavefront on the Web Download Goodies from the Web Find Menu... •/ Popup Help MEL Command Reference Node and Attrbuts Reference.., About Maya...
4Э-81
Рис. 1.79. Меню Help позволяет быстро отыскать информацию по любой теме
4. В разделе Assign New Hotkey (Присвоить новую «горячую» клавишу) выберите клавишу и модификатор команды (клавишу Ctrl или Alt) - рис. 1.78, Можно удалить текущие клавиатурные сокращения, которые определены для этой команды в настоящий момент, 5. Нажмите кнопку Assign. 6. Закройте окно Hotkey Editor.
Справочная система Maya Файлы помощи позволяют искать нужную тему по названию. Если вам нужна дополнительная информация по конкретной теме, то вы наверняка найдете все необходимое в файлах помощи. Меню Help (Помотць), которое находится в конце строки меню Maya, предоставляет три режима поиска информации: содержание {открываются все разделы справочной системы), алфавитный указатель и поиск по темам. Помимо этого, в нем содержатся ссылки на уроки и команда Find a menu Item (Найти элемент меню), позволяющая быстро отыскать нужный элемент меню (рис. 1.79).
50
Основы Maya
В Tutorials (Уроки) и Learning Movies (Обучающие фильмы) включены уроки и ссылки с простой навигацией, в которых предлагаются пошаговые инструкции выполнения стандартных задач Maya. Функции Contents (Содержание) и Search (Поиск) позволяют выбрать тему, по которой вы хотите получить более подробную информацию. Search отображает список ссылок, которые рассортированы по релевантности (рис. 1.80). Алфавитный указатель Maya напоминает указатель, который обычно находится в конце книги. При выборе из списка нужной темы на экране отображается определение и другая информация по этому вопросу (рис. 1.81). Функция Find a menu Item (Найти элемент меню) работает следующим образом: вы вводите название команды или инструмента и получаете путь к меню, которое содержит этот элемент (рис. 1.82). Данная функция может оказать неоценимую помощь в том случае, если вы знаете» как называется команда, но не помните, в каком меню она находится.
Рис. 1.80. В окне Contents and Search отображаются списки, предоставляющие дополнительную информацию по выбранному вопросу A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Symbols
! Express-1, Mel-1 != Express-1, Express-2, Mel-1 $ Ei-ipress-1, Express-2 % Express-I, Mel-1 % in expressions InstantMaya-1 %= Express-1 && Express-1, Mel-1 Рис. 1.81. В окне Index вы найдете определения функций и консультации по всем разделам файла помощи
£] 1«еСая Sensitive 5«rei Edit-5-Parent Edit->UnparEnl Deform->Eatt We-e-aParent Base «ire
Рис. 1.82. Функция Find a menu Item позволяет быстро отыскать гюбое меню, в котором находится интересующая вас команда
шигщня
ПО НЛТШЙСУ И ШРОЙДО
2 Интерфейс Maya можно целиком перенастроить (рис. 2.1). Это значит, что допускается изменять его, подстраивать под текущий проект и технологический процесс. Например, пока вы работаете с одной частью экрана - панелью или окном, все остальные элементы интерфейса могут быть скрыты. Однако даже к скрытым меню можно получить доступ при помощи меню Hotbox (рис. 2.2).
Рис. 2.1. Интерфейс Maya можно легко перенастроить
Меню Show позволяет скрывать и отображать объекты определенного типа. Просматривая объекты в рабочем окне, вы можете перемещать камеру вверх-вниз и вперед-назад, смещать ее параллельно фокальной плоскости и поворачивать вокруг объектов (откат, параллельное смещение и поворот камеры - термины киноиндустрии, обозначающие конкретные перемещения камеры}. Maya предоставляет множество способов выполнения одной и той же задачи, что позволяет оптимизировать рабочий процесс. Например, один из способов заключается в применении «горячих» клавиш, или клавиш оперативного вызова, которые можно определить практически для каждой команды. Прочитав эту главу, вы узнаете, как настроить интерфейс Maya и перемещаться по сцене.
52 Навигация по интерфейсу и настройка
Откат, смещение и поворот камеры Откат (dollying), параллельное смещение (tracking) и поворот камеры вокруг объектов (tumbling) позволяют смотреть на сцену с разных сторон и управлять расстоянием от зрителя по объектов. Вы всегда видите сцену сквозь камеру, а откат, смещение и поворот - способы ее передвижения, а значит, и возможность представить сцену по-другому. Эти функции являются одними из самых важных в Maya, поскольку при моделировании и создании сцены объект необходимо видеть со всех сторон и с разных расстояний. Кроме того, при выравнивании и размещении объектов очень большое значение имеет положение точки, из которой вы смотрите на сцену,
Рис. 2.2. Hotbox - это набор меню, который появляется под указателем мыши при нажатии клавиши Пробел
При параллельном смещении вида камера передвигается вверх, вниз или в стороны, не приближаясь к сцене и не удаляясь от нее. Это похоже на действие полосы прокрутки: вид как бы прокручивается, чтобы камера могла захватить объект, который в текущий момент не виден на экране.
Смещение вида 1. Установите указатель мыши в любом окне проекции. 2. Удерживая нажатыми клавишу Alt (или |м] в Macintosh) и среднюю кнопку мыши, переместите указатель мыши (рис. 2.3). Направление движения камеры совпадает с направлением движения указателя, Откат камеры зрительно увеличивает или уменьшает вид, объекты становятся ближе (увеличивается масштаб) или наоборот отдаляются (масштаб уменьшается).
Рис. 2.3. При смещении камеры сцена прокручивается вверх, вниз, вправо или влево
Откат, смещение и поворот камеры
53
Масштабирование вида 1. Установите указатель мыши в любом окне проекции. 2. Удерживая нажатой клавишу Alt/Ш, левую и среднюю кнопки мыши, переместите указатель влево, чтобы уменьшить вид, а чтобы увеличить - вправо (рис. 2.4}.
Рис. 2.4. Откат камеры используется для изменения масштаба как всей сцены, так и ее отдельных областей; откат вправо (внизу) увеличивает масштаб
Если требуется показать крупным планом определенный участок сцены, то, удерживая нажатыми клавиши Ctrl/Control и АИ/И. охватите его (с помощью только левой кнопки мыши) ограничивающим контуром, начав с левого края. Как только вы отпустите кнопку мыши, масштаб указанного фрагмента изображения будет увеличен, и фрагмент заполнит все окно. Если при очерчивании контура вы начнете перемещать указатель справа налево, то масштаб сцены уменьшится, и все исходное изображение поместится в охваченную контуром область (чем меньше ее площадь, тем меньше масштаб). Поворот вида обычно происходит вокруг центра объекта - это полезно делать, если нужно получить полное представление о трехмерном характере объектов или сцены. Например, вы можете повернуть камеру вокруг объекта, чтобы увидеть его спереди, сзади и сбоку под любым углом.
Поворот вида 1. Поместите указатель мыши в окно проекции Perspective.
Рис. 2.5. Здесь показано четырехоконное представление интерфейса Maya. Функция вращения камеры работает только в'окне перспективы
2. Удерживая нажатыми клавишу Alt/[S] и левую кнопку мыши, перемещайте указатель. Сцена начнет вращаться (рис. 2.5).
54
Навигация по интерфейсу и настройка Чтобы повернуть вид вокруг вертикальной или горизонтальной оси, во время вращения камеры удерживайте нажатой клавишу Shift.
Настройка разметки интерфейса В интерфейсе Maya есть два элемента, которые легко спутать друг с другом, поскольку их названия очень похожи: рабочее окно (рапе) и панель (panel). Рабочее окно — это по сути то же самое, что и окна проекций. Если вы внимательно рассмотрите главное окно приложения, разделенное окнами проекций, в каждом окне вы увидите что-то отличное от содержимого других окон. То же самое верно и в данном случае. В рабочем окне могут содержаться виды спереди, сверху, сбоку и в пер* спективе или любая панель. Панель - это разновидность окна Maya, которая предназначена для выполнения различных функций. Например, инструменты Hypergraph и Outliner представляют собой панели, в которых отображаются все узлы сцены, a Graph Editor - панель, используемая для редактирования анимационных кривых. Многие из этих панелей можно открыть в отдельных окнах (рис. 2.6) или в рабочем окне (рис. 2.7). Если панель открыта в рабочем окне, ее можно свернуть (рис. 2.8) или развернуть (рис. 2.9), нажимая клавишу Пробел. Таким же образом осуществляется управление рабочей областью: вы можете какоето время работать в одном окне проекции, а затем быстрым нажатием клавиши Пробел вернуться в четырехоконное представление.
Рис. 2.6. Панель Outliner открыта в отдельном окне
Рис. 2.7. Панель Ouliiner занимает все рабочее окно; ве можно свернуть или развернуть
Рис. 2.8. Свернув рабочее окно, вы получите доступ к другим окнам проекций
Настройка разметки интерфейса
55
Разработчики Maya оснастили программу современными, очень удобными в работе и настраиваемыми по желанию пользователя средствами. Они предусмотрели множество способов изменения интерфейса Maya и разметки рабочей области. Разметка - это компоновка окон проекций и панелей, которые размещаются в данных окнах (рис. 2.10).
Рис. 2.9. Если вы развернете рабочее окно, оно расположится поверх других окон, расширяя таким образом рабочее пространство
Рис. 2.10. Пользователь может создать свой вариант разметки рабочей области. В верхней части рисунка представлена разметка рабочей области, разбитой на четыре окна, в нижней части - на два окна проекции
56 Навигация по интерфейсу и настройка При первом запуске Maya вы увидите, что гю.умолчанию рабочая область разделена на четыре окна, которые соответствуют следующим видам: Тор (Сверху), Persp (В перспективе), Front (Спереди) и Side (Сбоку). Виды спереди, сбоку и сверху называются ортогональными, поскольку представляют собой ортогональную проекцию поверхностей на плоскость (рис. 2.11). Это позволяет просматривать сцены под любым углом зрения. Такой способ просмотра особенно важен, если нужно разместить и выровнять объекты в сцене. Комбинация из трех ортогональных видов позволяет оценить точное положение объекта по отношению к остальному содержимому сцены. Начинающие ЗВ-художники часто забывают проверить компоновку сцены во всех видах, а это может вызвать трудности при размещении других объектов. На виде спереди объект может быть размещен идеально, однако виды сбоку и сверху позволяют обнаружить ошибку. Вид в перспективе дает полное трехмерное изображение сцены {рис. 2.12). Изучив все четыре вида, вы сможете смотреть на сцену практически под любым углом.
View Shading Lighting Show Panefe •™— -•*-—-*—----;--- *вщиШВНВМН1
Shading Lighting Show Panels
В этой главе рассказывается, как изменить разметку всей рабочей области, создать и записать собственную компоновку или модифицировать только одну панель.
Замена рабочего окна видом Perspective В меню Panels рабочего окна, которое вы хотите заменить, выберите пункт Perspective Persp, можно поменять любое окно проекции на вид в перспективе vtew
tSBIii»ai
Рис. 2.15. На панели Graph Editor находятся анимационные кривые. Ее можно встроить в рабочее окно или открыть в отдельном окне
Look Through sd« Edit Layouts. На вкладке Layouts выберите название компоновки, которую будете редактировать (рис. 2.20).
60 Навигация по интерфейсу и настройка 2. На вкладке Edit Layouts в выпадающем меню Configuration выберите другую конфигурацию рабочей области (рис. 2.21). 3. Чтобы изменить размер частей окна, перетащите разделительные границы нумерованных блоков (рис. 2.22).
У Partels
i
Нф Panels] NewPenel] L.eyouts EdHUyotfe [History] Configurations Contents I Configuration 1ThreeParesSph,Bollom Single Pare Two P ines Slacked Two P snes Side by Side Three ^anes SplrtTop Three Cartes Split Left
4. Чтобы закрыть окно, нажмите кнопку Close.
Three Caries Split Righ! Three ^enes Stacked Three =enes Side by Side Four Panes c our Pones Split Top
Теперь можно получить доступ к новому варианту компоновки в меню Panels ^> Saved Layouts.
Рис. 2.21. Изменить число и расположение окон в рабочей области можно в поле Configuration вкладки Configuration
..Jn!.x|
Jr Panels Нф
Panels New Panel layouts Edit Leyouts History j Cord snts j Conltggir
"htee Fanes SplitBoPorri
•-
Close
Рис. 2.22. Размер рабочих окон рекомендуется изменять в соответствии с целью их использования. Например, окно Perspective можно сделать больше, увеличив область экрана
Настройка разметки интерфейса ;р(ау Sftxtew
Animate
Grid
Show wireframe Color... object Display Component ШщЛау NURBS Components NURBS Smoothness Polygon components Custom PohKjon Display Subdlv Surface Components subdiu Surface Smoothness
Deform Э •t Status Line "Shdr TlmeSlkter Range Slkter •f Command Line •" TOOl ВВЯ
Attribute Editor Tool Settings
Channel Box I Ufpr edtor Hde Ш. fflements Restwe UI Elements
Fast Interaction QjmeraAJght Manipulator -lointsize ЖНапсйейге
Рис. 2.23. Каждый элемент интерфейса или соответствующий раздел можно отобразить или скрыть, чтобы сэкономить пространство на экране
Рис. 2.24. Быстрый способ увеличить рабочее пространство - использовать команду Hide UI Elements
Скрытие или отображение элемента интерфейса В меню Display щелкните по пункту UI Elements и выберите элементы интерфейса, которые вы хотите скрыть или отобразить {рис. 2.23). Каждый элемент имеет два состояния видимости; он может быть скрыт или отображен. Если напротив названия элемента стоит галочка, значит, он отображается на экране. Вы можете скрыть элемент, щелкнув по его названию, или отобразить, если он скрыт.
Скрытие всех элементов интерфейса Выберите пункты меню Display ^> UI Elements ^> Hide UI Elements. Будут скрыты все элементы, кроме главного меню, меню рабочих окон и рабочей области с текущей компоновкой (рис. 2.24).
62 | Навигация по интерфейсу и настройка Отображение всех элементов интерфейса
•fJn irjLAV
I. ir:r'iing.'9t laclm.]
Grte
Выберите пункты меню Display ^> UT Elements "=> Restore UI Elements (рис. 2.25). Все элементы пользовательского интерфейса отобразятся на экране.
Head? Up Display
Скрытие и отображение главного меню и строки меню
Component Display
/ Status Line Channel Box/Layer Editor (рис. 2.44). В правой части экрана появится окно Channel Box. По умолчанию в окне Channel Box содержатся ключевые атрибуты выделенного объекта. Выполнив действия, описанные ниже, вы можете добавить атрибуты в список окна Channel Box.
70
Навигация по интерфейсу и настройка
Добавление предопределенных наборов атрибутов в Channel Box 1. Создайте или выделите объект, в который нужно добавить атрибут. 2. В меню Window выберите команды General Editors Channel Control (рис. 2.45). Откроется окно Channel Control. 3. На вкладке КеуаЫе выделите имя атрибута в области Non КеуаЫе окну Channel Control (рис. 2.46). 4. Нажмите кнопку Move
«щуе_ \.
5. Атрибут добавлен в список атрибутов КеуаЫе (рис. 2.47). 6. Чтобы закрыть окно Channel Control, нажмите кнопку Close. Теперь новый атрибут отображается в Channel Box (рис. 2.48).
^, Channel Control -rek/olve Object
Keynble j Locked | Non КеуаЫе DverrideTextunng ui'errideyisibilily
Ksyable rotated rotateY rotate Z scaleX scaleY scaleZ IransleteX NansleteY liansleleZ visibility
ntltaPn/HV
1
Close
Paint Effects... UV Texture Editor...
1 "
«Move
Рис. 2.46. В области Non КеуаЫе окна Channel Control содержатся атрибуты, которые можно добавить в Channel Box У channel Control - rkolve Object
168
_|nlx
Help
Kayabla j Locked '
trenslaleX trenslaleY IranslateZ
Attribute Editor... OuUlner... Hvpergraph...
•
Г? Change ali selected abjects ofthesarnetyP *
щЗнЯшаИИ rotateX rotate V rotaleZ , ile,scaleY
Component Editor... Attribute Spread Si « Connection Editor.,. Visor...
л
DtateAnisY oioteAKisZ olaleOrder otate Pi votT ran s 1 -steX otate Pi votTran si at в Y о late Pi voiTtar s 1 at s Z atetePivoK
Keyebie
Rendering Editors Animation Editors Relationship EtMors Set tings .'Preferences
168
Hdp
Non КеуаЫе cocriing displeyHendle displeyLocelA>is displayRolatePr/ot displayScBlePrvot ghosting identification inheritsTronsforrn interned ateObii=ct layerQverrideCebr
л
F СЬвпдейзб lectec objects ottrte s эте Л/ре Move»
Qose
ata Editor...
Script Editor... Command Shell...
\rtew Arrangement Suved Layouts Save Current Layout... Frame All in AH Wiev« A Frame Seedier! in Al views F Minimize Application Raise Main Window Raise Appkd tton Windows
Рис. 2.45. Окно Channel Control позволяет добавлять ключевые атрибуты или удалять их из списка Channel Box
Рис. 2.47. Чтобы добавить атрибуты в Channel Box, то есть сделать их ключевыми, переместите элементы списка Non КеуаЫе в список КеуаЫе Channels Object Translate X|1 008 Translate У t-_2.165 Translate Z 2 3 Rotate Й96 9 Relate Y -G Rotate Z O 595 |D 117'
Scale Z,1 i)3B Visibility |on
Рис. 2.48. В окне Channel Box отображаются все атрибуты, которые можно использовать при анимации
Настройка разметки интерфейса [~71 feptey Window
Animate
Deform
-•Grid
о Status Ше Shelf Time SideRange Sutler Command Une Helpline
Hde show Wireframe Color... Object Display Component Uisplay
Tool Box
NURBS Components NURBS Smootliriess
Tool Settings Channel Box / Layer Edtor
on Components custom Polygon Mspfay
Hfeteui Sememe Restore UI Elements
Subdlw Surface Components Suhdv Surface Smoothness
Рис, 2.49. Окно Attribute Editor можно открыть при помощи команд меню Display => Ul Elements f< Attribute Editor: rewolw 168 List Selected Fotus Attrbutes
Help
'l&ODo
Mm Max Range V [75шГ"~ SpnnaUV fi~~
Отображение и скрытие Attribute Editor Нажмите на кнопку Show or Hide the Attribute Editor Ц, которая находится справа от строки состояния. Выберите объект и просмотрите его атрибуты;
или В меню Display выберите пункт UI Elements О Attribute Editor (рис. 2.49). В правой части экрана появится окно Attribute Editor;
revolve_JBa revoJv
NURBS Surface History
В Attribute Editor содержатся дополнительные атрибуты, которых нет в Channel Box. Последнее окно обеспечивает быстрый доступ к тем атрибутам объекта, которые могут стать ключевыми в анимации. Список всех остальных атрибутов объекта находится в окне Attribute Editor. Оно остается пустым до тех пор, пока объект не выделен,
H
Form U j Form V Г "• > j Components > J NURBS Siatace Display TuxturR Map
или Нажмите комбинацию клавитп Ctrl/Control+a. Откроется окно Attribute Editor (рис. 2.50};
или В меню Window выберите пункт Attribute Editor (рис. 2.51). В правой части экрана появится окно Attribute Editor.
_> J Displacemenl Map >J Render Stels ^J Object Otsplay » , Node Behavior > f Extra AHributes LoadAUnbules I ' '-СоруТф
Рис. 2.50. Если редактор Attribute Editor открыт в новом окне, его можно перемещать и увеличивать
Animate
Deform
General Editors Rendering Editors Animation Editors Relationship Editor5 Settings/Preferences 1М!1Я!ЯЯ|! Outllner... Hypergraph.
Рис. 2.51. Окно Attribute Editor можно открыть в новом окне
72
Навигация по интерфейсу и настройка
Сглаживание и опции отображения Настройки отображения Maya позволяют изменить способ просмотра объектов в рабочем окне. Сцену можно просматривать в каркасном режиме* режиме тонирования с плавными цветовыми переходами, плоскостного тонирования., обрамления габаритным контейнером или в точечном режиме. Настройки отображения можно переопределять в соответствии с текущими задачами. Режим обрамления и точечный режим используются в сложных сценах, поскольку позволяют сократить время просчета вида при повороте камеры. Каркасный режим применяется при выделении компонентов (все компоненты объекта видны одновременно), а в режиме тонирования с плавными цветовыми переходами и плоскостного тонирования можно рассмотреть поверхность более подробно, что значительно упрощает процесс ее моделирования. Каждый режим полезен в конкретной ситуации, поэтому переключение между ними помогает оптимизировать рабочий процесс. В настройки отображения также входят опции аппаратного текстурирования и освещения, с помощью которых достигается быстрая обратная связь (то есть видимый результат) при добавлении в сцену текстуры или подсветки. У большинства опций есть соответствующие сокращенные клавиатурные наборы. Объекты можно отображать на одном из трех уровней сглаживания: низком, среднем и высоком. По умолчанию объекты отображаются при низком уровне сглаживания, но сглаживание можно переопределить с помощью «горячих» клавиш, описанных ниже. Низкий уровень сглаживания облегчает процесс выделения
Рис. 2.52. Меню Shading управляет эежимом отображения в каждом конкретном рабочем окне
компонентов, так как уменьшает количество отображаемых линий поверхности. Высокий уровень сглаживания используется при финапьной подгонке поверхности, когда нужно сфокусироваться на мелких деталях.
Изменение опций отображения в меню Shading В меню Shading (Тонирование) любого окна проекции выберите одну из следующих опций тонирования: Wireframe (Каркас), Smooth Shade (Тонирование с плавными переходами), Flat Shade (Плоскостное тонирование), Bounding Box (Обрамление) или Points (Точки) - рис. 2.52.
Сглаживание и опции отображения
73
«Горячие» клавиши для тонирования и сглаживания • клавиша 1 - Низкий уровень сглаживания (рис. 2.53); • клавиша 2 - Средний уровень сглаживания (рис. 2.53); • клавиша 3 = Высокий уровень сглаживания (рис. 2.53); Рис. 2.53. При низком сглаживании (слева) объект отображается с низким разрешением сетки триангуляции. При среднем сглаживании (в середине) объект воспроизводится с дополнительным, но не достаточным разрешением. При высоком уровне сглаживания (справа) достигается наилучшее представление формы поверхности
• клавиша 4 - Режим каркаса (рис. 2.М); • клавиша 5 - Режим тонирования (рис, 2.55); • клавиша 6 - Аппаратное текстурирование (рис. 2.56); • клавиша 7 = Аппаратная подсветка (рис. 2.57). ЧЛп*. During I "I II ' h , '
Рис. 2.54. Режим каркаса позволяет просматривать геометрию объектов на переднем и заднем плане
Рис. 2.55. По умолчанию в режиме тонирования поверхность отображается серым цветом, что позволяет показать ее конечную оболочку
Рис. 2.56. При аппаратном текстурировании в рабочем окне отображаются текстуры поверхностей
Рис. 2.57. Режим аппаратной подсветки суммирует все эффекты освещения сцены. Это грубый вариант конечной визуализации, который позволяет оценить результат сразу же после изменения положения источников света
74 Навигация по интерфейсу и настройка
Меню View Меню View (Просмотр) содержит команды управления целью камеры в окне проекции (рис. 2.58). Если создаваемая вами сцена оказалась сложной, вы можете отметить текущую точку наблюдения в рабочем окне, чтобы вернуться к этому представлению позже. Закладки чаще всего применяются в окне проекции Persp и позволяют возвращаться к ранее определенной пользователем точке наблюдения.
Запоминание текущей точки наблюдения
Ham Desertion
Рис. 2.59. Окно Bookmark Editor используется для создания закладок, фиксирующих представления, которые понадобятся вам позже
1. Б меню View рабочего окна выберите пункты Bookmarks (Закладки) => Edit Bookmarks (Редактировать закладки). Откроется окно Bookmark Editor (Редактор закладок) - рис. 2.59. 2. Нажмите на кнопку New Bookmark (Создать закладку). 3. В поле Name введите имя закладки (см. рис. 2.60). 4. Нажмите кнопку Apply (Применить), а затем Close (Закрыть), чтобы завершить работу.
Nam* Description
Рис. 2.60. Закладке присвоено имя dannys_camera Select Camera Previous view Mext V>sw Default Hams Look at Selection Frame ill Frame Selection Predefined Bookmarks Bookmarks Camera Settings Camera Attribute Editor.. Camera Tools
Рис. 2.58. Меню View используется для изменения, сохранения и восстановления точек наблюдения камеры
Сглаживание и опции отображения
75
Доступ к отмеченной точке наблюдения В меню View любого окна проекции выберите пункт Bookmarks О (имя закладки) рис. 2.61. В окне проекции отобразится отмеченное ранее представление сцены.
Рис. 2.61. Чтобы вернуться к сохраненному виду dannys_camera, выполните команды меню View Bookmarks 4 dannys_camera
•text View Default Home
Рис. 2.62. Команда Selecl Camera находится в меню View любого окна проекции
Меню View также используется для выбора камеры, через которую ведется наблюдение в настоящий момент, а также приближения выделенных объектов.
Выбор камеры текущего просмотра В меню View любого окна проекции выберите пункт Select Camera (Выбрать камеру) - рис. 2.62. Камера, через которую вы просматриваете объекты, будет выделена, а в правой части экрана откроется окно Attribute Editor, содержащее список свойств этой камеры (рис. 2.63). Чтобы удалить неиспользованные слои, выберите пункты меню Layer ^ Selecl Unused Layers (Слои Выделить неиспользованные слои) и затем выберите Layer ^> Delete Selected Layer(s) (Слои =* Удалить выделенные слои).
Рис. 2.63. В окне Attribute Editor содержатся все параметры выделенной камеры
76 Навигация по интерфейсу и настройка Отображение/скрытие слоя В Layer Editor щелкните в самом левом от имени слоя квадратике. Если слой в текущий момент отображается, он станет невидимым; если слой невидим, он вновь появится на экране.
Добавление примечания к объекту 1. Выделите объект, к которому вы хотите добавить примечание. 2. В меню Create выберите пункт Annotation (Примечание). Появится диалоговое окно Annotate Node (Узел примечания). 3. В поле Enter Annotation (Введите примечание} введите текст примечания, затем нажмите кнопку ОК. Появится примечание с линией, указывающей на объект.
ПРНМКШШ и ТЕКСГОШХ ост
3
Примитивы -этозаранее созданные геометрические наборы, которые упрощают составление более сложных форм. Их можно назвать строительными блоками ЗО-моделирования. Чтобы убедиться в этом, просто взгляните на окружающие вас объекты. Все предметы, какими бы сложными они ни казались, можно разбить на несколько примитивных форм. Присмотритесь к объектам, которые находятся в данный момент перед вами. Например, стул, выполненный из металлических труб, построен на основе множества цилиндров, а стена и дверь имеют форму расплющенного куба. Большинство объектов состоят из различных примитивов. Например, велосипед, Его колеса состоят из цилиндров (это любая спица} и тонкого тора, определяющего форму шины. Таким же образом с помощью примитивов из простой сферы создается лицо или из нескольких кубов получается здание.
78
Создание примитивов и текстовых объектов
На основе примитивов можно создать бесчисленное множество объектов, поэтому они и стали важной частью Maya и других ЗО-программ. Примитивы NURBS ускоряют рабочий процесс, потому что составляющие их кривые уже нарисованы и заменены геометрией поверхности. Можно изменять масштаб, растягивать, разрезать, перемещать, вырезать и перестраивать примитивы. Эти несложные фигуры становятся неотъемлемой частью вашего рабочего процесса и позволяют существенна сэкономить время, Примитивы Maya делятся на три группы: NURBS, полигоны (Polygons) и поверхности разделения (subdivision surfaces). Чтобы помочь вам разобраться, какие примитивы использовать для решения конкретной задачи, в этой главе подробно рассматриваются примитивы NURBS (рис. 3.1) и полигоны (рис. 3.2), причем для каждого из типов указываются его сильные и слабые стороны. Поверхности разделения являются более сложной темой и подробно описываются в главе 8.
Рис. 3.1. Примитивы NURBS (сверху вниз): сфера, куб, цилиндр, конус, плоскость, тор, окружность и квадрат
Рис. 3.2. Полигональные примитивы (сверху вниз}: сфера, куб, цилиндр, конус, плоскость и тор
Кратко о NURBS ("7э~| Взвешенные контрольные точки
Кратко о NURBS Кривые, поверхности и примитивы NURBS являются важной частью моделирования в Maya. Объекты NURBS используются для создания гладких (например, капот автомобиля) или острых, угловых поверхностей (например, дорожные знаки). Вы можете изменять поверхность объектов NURBS, работал всего лишь с несколькими взвешенными контрольными точками (рис. 3.3).
Рис. 3.3. Поверхности NURBS изменяются с помощью взвешенных контрольных точек
У каждой кривой или поверхности NURBS есть соответствующая ей степень, с помощью которой можно управлять сглаживанием объекта NURBS. При степени поверхности, равной 1 (параметр кривизны принимает значение linear (линейный)), все контрольные точки соединяются прямыми линиями и поверхность становится угловатой (рис. 3.4). При более высокой степени контрольные точки объекта NURBS соединяются сглаженными кривыми, что позволяет создать более ровную поверхность (рис. 3.5). Чем больше степень кривой, тем из большего количества точек она состоит. Более подробно о степенях NURBS рассказывается в главе 7.
Рис, 3.4. Поверхность со степенью 1 или параметром кривизны со значением linear
Рис. 3.5. Более высокая степень позволяет создавать сглаженные поверхности
80 Создание примитивов и текстовых объектов NURBS, или неоднородный рациональный би-сплайн, описывает объекты, формы которых определяются математическими уравнениями. К счастью, большинство математических преобразований программа оставляет за кадром. Би-сплайн ссылается на основную кривую, определяющую все объекты NURBS. При создании объекта NURBS используется множество кривых, чтобы затем получить каркасное изображение поверхности. Завершив работу с кривыми поверхности, программа как бы натягивает поверх них оболочку, чтобы создать конечную поверхность. Процесс создания поверхности на основе множества кривых называется лофтингом (lofting - создание по сечениям) - рис. 3.6. Объекты NURBS можно разбить на отдельные компоненты, которые совместно определяют форму объекта NURBS. Контрольные вершины (CV), редактирующие точки (edit points) и огибающие (hulls) используются для моделирования поверхности и определения формы кривых. Чтобы изменить форму объекта, можно работать сразу со всеми компонентами или с каждой по отдельности. Более подробно о компонентах NURBS рассказывается в главе 7.
Рис. З.Б. Верхний объект состоит только из кривых, а нижний имеет еще и оболочку
Примитивы NURBS f81
Примитивы NURBS Примитивы NURBS представляют собой набор предопределенных кривых и поверхностей. В Maya существует восемь примитивов NURBS: сфера (sphere), куб (cube), цилиндр (cylinder), конус (cone), плоскость (plane), тор (torus), окружность (circle) и квадрат (square) - рис. 3.7.
Рис. 3.7. Примитивы NURBS используются в качестве составляющих для более сложных моделей NURBS Sphere Optima Eil IE Hilt,
««*вовд.а
Оияг»йп«1 00000
,'-'P«t-> 00000
00000
Appr»
Рис. З.8. Атрибуты примитива изменяются в диалоговом окне Options SHAPES nmlisSpheieShapel , INPUTS Radius Т tart Sweep 0 End Sweep i360 DegrealCubic
Height Ratia-J
Рис. З.9. История создания позволяет изменить атрибуты существующей поверхности
6 3-81
Предопределенные примитивные поверхности не только позволяют сэкономить время при создании простых объектов- их можно также использовать как составляющие более сложных форм. Окружность и квадрат - это кривые NURBS, к которым поверхность не прикреплена; остальные шесть примитивов NURBS представляют собой предопределенные поверхЕгости, которые можно без какой-либо предварительной обработки помещать в сцену Maya или применять для построения сложных моделей. Каждый примитив имеет ряд атрибутов, с помощью которых можно получить объекты самых разных форм. Чтобы создать объект, атрибуты примитива следует изменить в диалоговом окне Options (Настройки) - рис. 3.8. В большинство примитивов входит история создания, которая прикрепляется к узлам их поверхности. Можно изменить и отрегулировать свойства поверхности после того, как она была создана (рис. 3.9). Атрибуты истории создания каждого примитива отображаются в Channel Box под заголовком makeNurb. В этой главе рассказывается, как создавать примитивы NURBS и изменять некоторые их атрибуты (как до, так и после создания объекта). Более подробно об истории создания рассказывается в главе 1.
82 Создание примитивов и текстовых объектов
Создание примитивов NURBS
Примитив тор —i Пр1ИМИТИ6 ПЛОСКОСТ1
Доступ к примитивам NURBS можно получить, выполнив команды меню Create => NURBS Primitives (рис. 3.10). Чтобы создать примитив, нужно щелкнуть по его имени. Далее рассказывается, как создать примитив с помощью Hotbox. Есть еще один, более быстрый способ создания примитивных поверхностей NURBS: следует щелкнуть по соответствующей кнопке в разделе Surfaces (Поверхности) полки (shelf) - рис. 3.11.
Примитив конус
Примитив цилиндр — Примитив куб Примитив сфера
Рис. 3.11. Чтобы быстро создать примитивы NURBS, щелкните по соответствующей кнопке в полке Surfaces
При создании примитива поверхности или кривой центр объекта помещается в начало координат сцены (точка с координатами О, О, 0). Таким образом, большинство объектов центрируется относительно оси Y (одна половина объекта находится над осьго, а другая - под ней) рис. 3.12. Исключением является конус, центр которого помещается на основании. Чтобы создать примитивы NURBS, выполните описанные далее действия.
Create
Display
Window
Polygon Prfrrttlves Subdiv Primitives Volume Primitives Lights Cameras CV Curve Tool EP Curve Tool PencH Curve Tool Are Tools
Uniting/Shading
Cube Cylinder Cone
a
Torus Grcle Square
о о о
fl
a
Measure Toote Text Construction Plane Locator Empty Group Sets
Рис. 3.10. Чтобы создать примитивы NURBS, выберите пункты меню Create NURBS Primitives
Рис. 3.12. Центр пэимитива находится в начале координат сцены
Примитивы NURBS f 83 Display JWindow 1
NURBS Primitives Polygon Primitives Subdlv Primitives Volume primitives Limits Cameras CV Curve Tool EP curve Too* Perid Curve Tool Arc Tools Measure Tools
^^НкшЩыИИ Cube Cylinder Cone Plane Torus Circle Square
t *
a
Text
о
Construction Plane Locator
№
Empty Group Sets
1 n
т a a т a
a a.
t>
Рис. 3.13.6 подменю NURBS Primitives выберите имя примитива, который нужно создать
Рис. 3.14. Примитив NURBS появится в начале координат сцены Maya
Создание примитива NURBS с помощью главного меню 1. Выполните команду меню Create => NURBS Primitives. 2. Щелкните но названию примитива, который требуется создать; в данном 'Случае моделируется сфера (рис. 3.13). Примитив NURBS появится в начале координат сцены Maya (рис. 3.14). Hotbox позволяет значительно сэкономить время при создании объектов и примитивов, поскольку воспользоваться им проще, чем выполнить команды главного меню. Вызвать меню Hotbox можно из любой части окна Maya, сократив тем самым время получения доступа к меню.
84 Создание примитивов и текстовых объектов Создание примитива NURBS с помощью Hotbox 1. Чтобы отобразить меню Hotbox, нажмите и удерживайте клавишу Пробел. 2. В меню Create, которое находится в меню Hotbox, выберите подменю NURBS Primitives. 3. Щелкните по названию примитива, который требуется создать; в данном случае моделируется куб (рис. 3.15}. Примитив NURBS появится в начале координат сцены Maya (рис. 3.16).
Рис. 3.15. Чтобы выбрать подменю NURBS Primitives, можно воспользоваться меню Hotbox
В разделе Surfaces (Поверхности) полки содержатся кнопки для быстрого доступа ко всем поверхностям примитивов NURBS (рис. 3.17). Выбирая примитивы в меню Shelf, вы можете сократить процесс создания на два или три шага, которые нужно было бы выполнить, чтобы найти тот же примитив в меню Create.
Рис. 3.16. Примитив NURBS создается в начале координат сцены Maya
Рис. 3.17. По умолчанию в полке содержатся значки сферы и нонуса
Примитивы NURBS |~85 Создание примитива NURBS с помощью полки В полке выберите значок нужного вам примитива NURBS (например, сферы ф или конуса sfa . Примитив появится в начале координат сцены Maya (рис. 3.18). Если полка не отображается на экране выполните команды Display UI Elements о Shelf (рис. 3.19).
Рис. 3.18. В полке Surfaces щелкните по значку примитива NURBS. В данном случае выбран конус Display Window ' Grid Heads Up Display
ЦЩЗ r*te show
Wireframe Color,.. Object Display Component Display гчШВЗ Components NURBS Smoothness
( t
•* ComnidridLfrw •" HdpLlne
Attribute Editor
IWIygorr Caraponeits Custom Polygon Display SUbdiv Surface Components sutidiv Surface Smoothness
Чтобы добавить в полку примитивы или другие объекты, выделите элемент в главном меню, удерживая нажатыми клавиши Shift и Ctrl/Control. Выбранная в меню команда и пункты меню, которые выделены в текущий момент, сохранятся в полке. Допустим, вам нужно переопределить атрибуты объекта перед тем: как добавлять его в меню Shelf. Произведите необходимые изменения параметров в диалоговом окне Options примитива. Например, поместите в полку одну сферу с углом конечной точки развертки в 20° и еще одну с углом конечной точки развертки в 360°. В этом заключается еще один способ ускорить работу с часто используемыми примитивами.
hide UI Hements Restore UI й«вмй5
i' Fastlnta-action Joint size IK Handle Size
Рис. 3.19. Чтобы отобразить окно Shelf, выберите пункты меню UI Elements => Shelf
Чтобы удалить элементы из меню Shelf, перетащите их в корзину, удерживая нажгтой среднюю кнопку мыши.
86
Создание примитивов и текстовых объектов
Изменение атрибутов примитивов NURBS У каждого примитива NURBS есть определенный набор атрибутов. Некоторые атрибуты являются общими для всех примитивов NURBS, другие же присущи лишь одному или двум. Переопределяя атрибуты, можно изменять поверхности примитивов. Все атрибуты примитива NURBS изменяются одним и тем же способом. В этом разделе рассказывается о том, как переопределить радиус примитива NURBS. Чтобы изменить другие атрибуты объекта, выполните те же действия. В следующем разделе описывается большая часть атрибутов примитивов NURBS. Радиус является общим атрибутом для следующих примитивов NURBS: сферы, конуса, цилиндра, тора и окружности (рис. 3.20).
Рис. 3.20. Радиус определяет размеры объекта Create
Display
Wjndcw
Polygon Primnivee SubdlvPrMUves Volume Primitive»
Lighting/Shading Sphere
a Я
•ШЦЦ.ЦДИ [HI
Cameras
Cone Plane тогш
О a n
CV Curve Toot EP Curve Teal Pencl Curve Tod Arc Tools Measure Tools Text
Определение радиуса с помощью меню Create 1. В меню Create выберите пункт NURBS Primitives (Примитивы NURBS). 2. Щелкните по значку окошка рядом с названием примитива, радиус которого требуется задать, в данном случае определяется радиус цилиндра (рис. 3.21). 3. В диалоговом окне Options (Опции) выбранного примитива с помощью ползунка Radius установите значение, соответствующее половине нужного диаметра примитива (рис. 3.22).
Construction Plane Locator Empty Group sets
Рис. 3.21. Выберите значок рядом с названием примитива, радиус
Рис. 3.67. Щелкните в поле Text и введите новый текст
2. В диалоговом окне Options щелкните в поле Text и введите новый текст (см. рис. 3.67). 3. Щелкните по стрелке рядом с полем Font и выберите шрифт текста. Нажмите кнопку ОК. 4. Убедитесь, что параметру Туре присвоено значение Trim (Вырезка) - рис. 3.68, 5. Нажмите кнопку Create для завершения операции. На сцене Maya появится текст, левый нижний край которого совпадает с началом координат, как на рис. 3.64.
Рис. 3.68. Убедитесь, что в списке Туре выбран переключатель Trim
Третий тип текстового объекта - Poly (Полигональный). Он более, чем остальные типы, подходит для встраивания текста в другие полигональные поверхности, Для объектов этого типа в Maya имеются многочисленные опции управления количеством полигонов, составляющих текст, а также другие полезные атрибуты текста.
102 Создание примитивов и текстовых объектов В объект Poly включена история создания, в частности, присоединения поверхностей к кривым, что позволяет при работе с кривыми изменять форму отдельной буквы.
Создание текстового объекта Poly
,,ln
Melo
F««;Xtnti4-cn-Plsn
i^
О Ч™1»
Tfpt STranglts Ti ssellalior
Mjthod бОгнп! ft
S:
indard
ОюЯ HHgtHltKie'o 100*
1. В меню Create щелкните по значку рядом с пунктом Text.
;
™р-
ItUMUl
luleunn
OOHO
Qromr Fii чаттт
f»_
0
Cf 0
»»»..•
ПТПЙ '
Pmmi
""'"'"'
шлшяиж-д»
ИИ
2. Б диалоговом окне Options щелкните в поле Text и введите новый текст. 3. Щелкните по стрелке рядом с полем Font и выберите шрифт текста. 4. Убедитесь, что параметру Туре присвоено значение Poly (Полигональный). Для достижения наилучших результатов воспользуйтесь установками по умолчанию (рис. 3.69). 5. Нажмите кнопку Create, чтобы завершить операцию. На сцене Maya появится текст, левый нижний край которого совпадает с началом координат (рис. 3.70).
Рис. 3.69. Убедитесь, что в разделе Туре выбран переключатель Рог/
Рис. 3.70. На сцене Maya появится текст, левый нижний край которого совпадает с началом координат
Присваивание названия объектам ГТОЗ
Присваивание названия объектам
Рис. 3.71. По умолчанию седьмая созданная на сцене сфера NURBS будет называться nurbsSphere?
= Tfinslate ¥ Tridilst! 2 Rotatt x Rome Y Rota» г
Рис. 3.72. В верхнем части окна Channel Box выделите название объекта, присвоенное по умолчанию
Had in i Stair Sweep _ £ n a iivttp '
!!ЁШ=И
%y
Type
Select AI invert sete^sri Select M by Type Quick Seiecl Sets Pdrrt Selection Tool
* '
> 'I
Duplicate Duplicate with Transform
Ctrl id О
Group
Ctrl+g
|
darnve^eet
v~ э
Le«l ofDetail Parent Ur*>arent
Рис. 4.33. Присвойте списку выделения значащее имя, чтобы при необходимости быстро отыскать набор в меню Quick Select Set
Рис. 4.34. Создав набор быстрого выделения, вы можете заново производить выделение, выбрав пункты меню Edit & Quick Select Set ^ [имя набора]
120 Режимы выделения, скрытие и шаблоны Скрытие выделенного объекта 1. Выделите объект, который необходимо скрыть (рис. 4.35). 2. В меню Display выберите пункт Hide *$ Hide Selection (Скрыть => Скрыть выделенные объекты) или нажмите клавиши Ctrl/Control+h (рис, 4.36). Выделенный объект будет недоступен для просмотра (рис. 4.37).
Display Window
Lightlnii/Shadng
Grid Heads Up Display UI Elements
a * ' Hide unsrtected objects ftlt+h
Рис. 4.36. Выполните команды меню Display => Hide ^ Hide Selection
Отображение всех скрытых объектов В меню Display выберите пункты Show => All (Отобразить => Все) - рис. 4.38. Все скрытые объекты отобразятся на экране.
Рис. 4.37. Выделенные объекты не отображаются на экране. Затем вы можете отобразить все скрытые объекты или объект, скрытый последним Display window Lighting/ shading Grid ''' Heads Up Display Ul Semenls
a * '
Hide Wireframe CQkM"«. object Ыв[йа¥ component Display
Рис. 4.38. Чтобы отобразить все скрытые объекты, выберите пункты меню Show АН
Рис. 4.35. Выделите один объект или несколько объектов, которые требуется скрыть
Выбор объектов и использование Pick mask 1121 Отображение скрытого объекта
Wireframe Color...
Рис. 4.39. Чтобы на экране появился объект, скрытый последним, выберите пункты меню Show Lights => Spot Light.
Рис. 523. С помощью двух манипуляторов можно более точно управлять теми объектами, которые освещает источник света, и направлением света
2. На панели инструментов щелкните по кнопке Show Manipulator *£. Теперь один манипулятор источника света расположен в его основании, а другой в точке освещения {рис. 5.23).
134 Преобразование объектов и компонентов 3. Выделите манипулятор в основании источника света (рис. 5.24). 4. Переместите манипулятор вверх по оси Y. Источник света передни га ется вместе с манипулятором, но продолжает указывать на точку, отмеченную вторым манипулятором (рис. 5.25). 5. Выделите манипулятор, который находится в центре окружности, создаваемой светом источника, 6. Переместите манипулятор по оси Z. Источник света останется на месте, но направление его лучей изменится (см. рис. 5.26}. 7. Щелкните дважды по маленькому светло-синему кольцу, находящемуся рядом с объектом. Манипуляторы превращаются в кольцо, опоясывающее световой
Рис. 5.25. Манипуляторы можно перемещать по одному или вметге, чтобы сохранить дистанцию между источником света и точкой освещения
Источник света перемещается при помощи этого манипулятора
Направление источника света изменяется при помощи этого манипулятора
Рис. 5.24. Чтобы переместить источник света, передвигайте прикрепленный к нему манипулятор
Рис. 5.26. Чтобы направить свет непосредственно на объект, сгруппируйте манипулятор, определяющий течку попадания лучей, и объект. Источник света всегда будет направлен на этот объект
Перемещение, вращение и масштабирование объектов 135 конус. Щелкните но этом}' кольцу, чтобы интерактивно изменять узлы истории создания (рис. 5.27). 8. Щелкните по кубику, который находится на окружности, очерчивающей конус, в одном из режимов, активированных нажатием на кольцо, и перетащите указатель. При перемещении мыши интерактивно изменится угол раствора конуса {рис. 5.28).
Рис. 5.27. Для большинства объектов будет отображаться синее кольцо, с помощью которого можно получить доступ к узлам Input
Использование инструмента Lasso selection для выделения набора компонентов 1. Создайте примитив - сферу NURBS, 2. Нажмите клавишу F8. 3. На панели инструментов щелкните по кнопке инструмента Lasso selection (Произвольное выделение) CV 4. Перетащите указатель так, чтобы очертить окружность вокруг контрольных точек, которые вы хотите выбрать (рис. 5.29).
Рис. 5.28. Угол конуса определяет ширину светового пучка
5. Отпустите кнопку мыши. Контрольные точки будут выделены (рис. 5.30).
Рис. 5.29. Окружность, очерченная инструментом Lasso Selection, замкнется после того, как вы отпустите кнопку мыши
Рис. 5.30. Верхние контрольные точки выделены, так как они входили в область выделения
136 Преобразование объектов и компонентов
Опции копирования Инструменты копирования Maya позволяют моделировать объекты с повторяющейся геометрией, например лестницы. Для построения лестницы необходимо взять всего лишь один вытянутый куб и выполнить копирование, с помощью которого можно создать целую лестницу при минимальном количестве усилий (рис. 5.31). Как для простого, так и для сложного копирования объектов, включающего в себя повороты, перемещения и масштабиро вания, используется инструмент Duplicate (Копировать). Более того, среди опций Duplicate есть дополнительные функции для зеркального отображения объектов и создания их экземпляров. Объекты можно скопировать вместе с узлами INPUTS (историей создания) или без них - рис. 5.32. (Более подробно об истории создания рассказывается в главе 1.) Следует запомнить, что по умолчанию копирование этих узлов отключено.
Рис. 5.31. Лестници была построена из двух объектов с помощью одной операции копирования
niafceNurbSfih ere 1 _ Radius ЫШ~ 51 art Sweep О ЕМЭяеар ГЗБО Degree [Cubic Sections [8
Рис. 5.32. В узле Input находятся атрибуты сферы, принадлежащие истории создания, которые можно .J редактировать
Зеркальное отражение объектов и создание экземпляров Помимо перемещения объектов, инструмент Duplicate используется для создания зеркального отражения объекта (обращенной копии оригинала). Зеркальное отражение используется при моделировании симметричных частей тела {глаз, ушей, рук и ног), так как они практически совпадают друг с другом (рис. 5.33). Если вы выполните операцию зеркального отражения одного из подобных объектов, например уха, вы сможете простым нажатием кнопки мыши создать второй объект, точно отраженный относительно первого.
Рис. 5.33. Зеркально отразив одну руку, вы сэкономите время на создании второй руки
Опции копирований
Рис. 5.34. Экземпляры объекта повторяют изменения, внесенные в оригинал
Помимо копирования и зеркального отображения можно создавать экземпляры (instances) объектов, которые сохраняют связь с оригиналом (рис. 5.34). Если вы будете редактировать оригинал, все его изменения немедленно отразятся и на экземплярах. Например, чтобы построить множество одинаковых колонн, создайте одну колонну, а затем несколько ее экземпляров, которые и будут остальными колоннами. Если в дальнейшем вы решите изменить вид колонн, достаточно будет переопределить параметры одной, а остальные обновятся автоматически.
Копирование объекта 1. Щелчком мыши выделите объект.
Undo R«do Repeal "NURBS (
2. В меню Edit щелкните по значку рядом с пунктом Duplicate (рис. 5.35). Откроется окно Duplicate Options (Опции копирования). 3. В поле Number of Copies (Число копий) введите нужное число копий (рис. 5.36).
Ь«!К! All Stfeei Hltra«*nr \nven select «HI ielKi *li bv Type QuU.1, Select Srts Paint Selection Tool Oi.plIran «i Group 1>пцгадо Level of Det Pirsnt
i -i
Рис. 5.35. В меню Edit щелкните по значку рядом с пунктом Duplicate, чтобы открыть окно Duplicate Options
Duplitare Opuoni
Dumber flf Copie
Рис. 5,36, В поле Number of Copies введите нужное число копий
4. Нажмите кнопку Duplicate. Будет создано указанное вами число копий, и все они будут размещены в одном и том же месте, то есть поверх оригинала.
138 Преобразование объектов и компонентов Копирование объекта с вращением
Duplicate Options Edit
Н*1р Translate (, )оос
1. Щелчком мыши выделите объект. 2. В меню Edit щелкните по значку рядом с пунктом Duplicate. Откроется окно Duplicate Options. 3. Выберите значение поворота для каждой дополнительной копии и введите это число в поле Rotate той оси, вокруг которой будут повернуты объекты (рис, 5.37). Эти поля соответствуют осям X, Y и Z (слева направо). Если для преобразований вы использовали сферу, то вращение будет заметно только в режиме каркаса.
sw« i 1.3000
fo.OQOO
k 0000
|c oooo
jc oooc
1 1 OOOO
Il.OOOO
1
Nimibcrof Copies 1 DuptkltF
Apply
Clos*
Рис. 5.37. Введите ьужное значение поворота в первом поле атрибута Rotate. Первое поле соответствует вращению вокруг оси X Точка центра трансформаций
4. Чтобы скопировать объект, нажмите кнопку Duplicate. Тот же метод используется для перемещения копий или их масштабирования. Настройки копирования можно вернуть в первоначальное состояние, выбрав в окне Duplicate Options пункты меню Edit Q Reset Settings (Правка ^ Сбросить настройки). Теперь, когда вы имеете общее представление о том, как копировать объекты, давайте перейдем от теории к практике и создадим простую лестницу. Воспользуемся тем же методом, который применялся для со здания копии с одним поворотом, и вы полним операции Translate, Rotate и Scale одновременно. При создании копии с перемещением необходимо правильно определить центр трансформаций, чтобы объекты вращались вокруг нужной оси (рис. 5.38).
Рис. 5.38. Размещение центра трансформаций определяет конечное местоположение копии
Опции копирования И 39
Создание простой лестницы Channel
Objetr
'CUBE Translate X Translate Y Translate Z Rotitt X Rotate ¥ Rotate Z Suslf X Susie Y Scale Z Visibility
Cftinticii
ICUGE ;
Ti an slate X Tr an slate Y Translate 2 Rotate X Rotate Y Rotate Z Scale X ScaleY Scale Z Visibility
0 05 0 0 0 0 1 1 1
on
Рис. 5.39. Переместите куб так, чтобы его нижняя грань оказалась на сетке, указав в поле Translate Y значение 0,5
Objecl
0 0.5 0 0 0 0
6 1 1 on
Рис. 5.40. Чтобы увеличить объект в 6 раз по оси X, введите в поле Scale X значение 6
1. В меню Create выберите пункт Poly Primitive Cube (Полигональные примитивы О Куб). В начале координат будет создан куб. 2. В окне Channel Box в поле Translate Y введите значение 0,5 и нажмите клавишу Enter (рис. 5.39). Куб переместится вверх таким образом, что его основание окажется на сетке. 3. В окне Channel Box в поле Scale X введите 6 и нажмите клавишу Enter (рис. 5.40J. Куб вытянется и превратится в параллелепипед. 4. Нажмите клавишу w или на панели инструментов щелкните по кнопке инструмента Move Щ. 5. Чтобы перейти в режим редактирования центра трансформаций, нажмите клавишу Insert/Home. 6. С помощью манипулятора оси X переместите центр трансформаций таким образом, как показано на рис. 5.41.
Рис. 5.41. Центр трансформаций определяет точку, вокруг которой будет поворачиваться будущая лестница
7. Чтобы выйти из режима редактирования, еще раз нажмите клавишу Insert/ Home. 8. В меню Edit щелкните по значку рядом с пунктом Duplicate, чтобы открыть окно Duplicate Options.
140 9.
Преобразование объектов и компонентов Установите параметры инструмента Duplicate следующим образом (см. рис. 5.42): Translate; О, 1, 0. Каждая новая копия объекта будет перемешаться на одну единицу вверх по оси Y относительно ранее созданной. Высота ступеньки равна единице, поэтому каждая копия будет находиться точно на предыдущей; - Rotate: 0, 15, 0. Каждая копия будет повернута вокруг оси Y на 15° относительно предыдущей; - Scale: .95, .95, .95. Размер каждой копии будет на 5% меньше размера предыдущей. По мере продвижения вверх размеры ступенек лестницы уменьшаются.
Dupfnate Options 0 OQ'X.
О 0000
Number cf Copies
15
ООООО
20
3«or1d
" S-
Рис. 5.42. Чтобы создать лестницу, имея в своем распоряжении только одну ступеньку, определите параметры инструмента Duplicate, как показано на рисунке
10. В поле Number of Copies введите значение 20. Лестница будет состоять из 21 ступеньки. 11. Щелкните по кнопке Duplicate. Программа создаст заданное вами число копий, которые вы повернули и масштабировали, а затем расположили точно друг над другом (рис. 5.43). Перед тем как копировать объект, нужно проверить параметры инструмента. Если вы не сбросите предыдущие установки, они сохранятся при новом вызове окна, Чтобы вернуться к установкам по умолчанию, откройте окно Duplicate Options и выполните команды меню Edit c> Reset Settings.
Рис. 5.43. Если параметры Duplicate определены правильно, то построить лестницу можно одним нажатием кнопки мыши
Перед копированием переместите центр трансформаций на некоторое расстояние от левой грани объекта по оси X, чтобы освободить место для лестничного пролета (рис. 5.44). Рис. 5.44. Переместите центр трансформаций, чтобы освободить место для лестничного пролета
Опции копирования
Рис. 5.45. Вы можете создать половину лица, а затем зеркально отобразить ее, чтобы получить лицо целиком
141
Зеркальное отражение объекта создает его обращенную копию. При помощи этого метода художники моделируют лицо персонажа; сначала рисуется его половина, которая затем отражается относительно оси1 (рис. 5.45J. Ось при зеркальном отражении исходит из центра трансформаций. Это означает, что чем больше расстояние между объектом и центром трансформаций, тем больше будет расстояние между оригиналом и его зеркальной копией. Данная команда часто используется совместно с командой создания экземпляра. Таким обралом, художник сможет продолжать работу с начальной половиной лица, а изменения будут вноситься в обе части (рис. 5.46). Более подробно на создании экземпляров мы остановимся после выполнения следующей задачи. Команда создания экземпляров также используется для размещения объектов на одинаковом расстоянии от какой-либо оси, что позволяет моделировать точно расположенные зеркальные копии (рис. 5.471.
Рис. 5.46. Совмещая создание экземпляра и зеркальное отражение, можно изменять обе части лица, работая только с одной половиной
Рис. 5.47. Идеальными объектами для зеркального отражения являются симметричные части тела. Положение центра трансформаций на сцене определяет, как далеко друг от друга будут находиться зеркальные объекты
В следующем примере мы будем использовать команду зеркального отражения применительно к сфере, чтобы в итоге создать глаза персонажа.
В случае зеркального отражения корректнее говорить не об оси, а о плоскости, относительно кото рой отражается объект. Автор имеет в виду ось, которая лежит s плоскости зеркального отражения. Прим. науч. ред.
142 Преобразование объектов и компонентов Зеркальное отражение объекта 1. В меню Create выберите пункты NURBS Primitive => Sphere (Прими тины NURBS => Сфера) или выделите объект, который нужно зеркально отразить. 2. В окне Channel Box в поле Translate X введите -2 (рис. 5.48). Объект переместится на две единицы в отрицательном направлении по оси X.
Chafuieig Object lluliele3 Translate X--2 Trai^slale Г О Translate Z.D Rotate X=C Ratal» Y 0 Rotate I 0 Scale X 1_ Зсаш Y '" State I.',
on
Рис. 5.48.6 окна Channel Box в поле Translate X введите -2, чтобы переместить объект на две единицы в отрицательном направлении по оси X
3. Нажмите клавишу w или на панели инструментов щелкните по кнопке инструмента Move Hfc. 4. Чтобы перейти в режим редактирования центра трансформаций, нажмите клавишу Insert/Home. 5. Удерживая нажатой клавишу х, переместите точку центра трансформаций в начало координат (рис. 5.49). Клавиша х привязывает преобразования объекта к сетке. Это гарантирует, что центр трансформаций переместится точно в начало координат.
Рис. 5.49. Чтобы расстояние от копии до начала координат было равно расстоянию от исходного объекта до центра трансформаций, переместите ее в начало координат
6. Чтобы выйти из режима редактирования, снова нажмите клавишу Insert/ Home. 7. В меню Edit щелкните по значку рядом с пунктом Duplicate. Откроется окно Duplicate Options. 8. В окне Duplicate Options в меню выберите пункты Edit "=> Reset Settings (Редактирование с> Сбросить установки), чтобы сбросить старые установки, л затем введите в поле Scale X значение -1. 9. Щелкните но кнопке Duplicate. Зеркальная копия помещена на таком же расстоянии от центра трансформаций, что и исходный объект (рис. 5.50).
Рис. 5.50. Зеркальная копия помещена на таком же расстоянии or начала координат, что и исходный объект
Опции копирования 143 Создание экземпляров объектов позволяет значительно сэкономить время как при моделировании, так и при визуализации. Объект-экземпляр будет повторять все изменения исходного объекта, поэтому с помощью данной функции очень удобно создавать экземпляры объекта, у которого должны быть внешне идентичные копии в другом месте сцены (рис. 5.51). Как уже говорилось, экземпляр копирует все изменения объекта, однако его можно масштабировать, поворачивать и перемещать независимо от оригинала. Рис. 5.51. Чтобы упростить редактирование, были созданы экземпляры нефтяных баков. Затем экземпляры повернули под разными углами, чтобы скрыть их идентичность
Создание экземпляра объекта 1. Щелчком мыши выделите объект. 2. В меню Edit щелкните по значку рядом с пунктом Duplicate. Откроется окно Duplicate Options. 3. В поле Translate X введите 2, а в остальные поля Translate и Rotate - О (рис. 5,52). В данном примере совместно с командой создания экземпляра используется перемещение, чтобы копии не накладывались на оригинал.
Рис. 5.52. Введите в поле Translate X (поле слева) значение 2 * Instance
Рис. 5.53. Выбрав в поле Geometry Type переключатель Сору, вы просто скопируете объект. Выбор опции Instance позволяет создать дополнительную связь с начальным объектом
4. В поле Geometry Type (Тип геометрии) выберите переключатель Instance (Экземпляр) - рис. 5.53. 5. Щелкните по кнопке Duplicate. Копня объекта представляет собой экземпляр (или виртуальную копию) оригинала. 6. Выделите один из объектов и нажмите клавишу F8, чтобы перейти в режим выбора компонентов.
144 Преобразование объектов и компонентов 7. Чтобы выделить нужные компоненты объекта, захватите в рамку его верхнюю треть (рис. 5.54). 8. Нажмите клавишу w и переместите компоненты в любом направлении. Заметьте, что другой объект повторит перемещение выделенной поверхности (рис. 5.55). Нельзя изменять компоненты экземпляра независимо от объекта-оригинала.
Часто при копировании объекта требуется, чтобы дублировалась также история его создания. Поставьте флажок Duplicate Input Connections (Скопировать входящие соединения) в окне Duplicate Options, и объекты будут иметь общий узел Input. Эю позволяет изменять как оригинал, так и его копии при переопределении атрибутов этого узла.
Рис. 5.54. Захватите в рамку верхнюю треть объекта, чтобы выделить нужные контрольные точки
Рис. 5.55. Другой объект повторит перемещение выделенной поверхности, но в противоположном направлении, как зеркальное отражение
Опции копирования [J45
Копирование объекта с историей создания
Charyiete object tmrbsSpltejeJ Ггэп slate X 0 Translate y.D
1. Выделите объект с узлом Input, например сферу (рис. 5.56). 2. В меню Edit щелкните по значку рядом с пунктом Duplicate. Откроется окно Duplicate Options.
SHAPtS 11» i lisSp h e caS h ape? INPUTS m ,i ke N и г h S |ih «(e? Radius I) 5C4 Start Swef p ID gad Sweep !jGP Deg^ee'uibic Seclia^s 8 Spate 14 H sight Ratio! 2
Рис. 5.56. В узле Input сферы содержится история ее создания, которую можно редактировать
Number <sl Ccpii
SI Quplicjis Inpui Connections
Рис. 5.57. Чтобы скопировать входящие соединения в новый объект, отметьте галочкой флажок Duplicate Input Connections в окне Duplicate Options
Рис. 5.58. Определите с помощью ползунка Number of Copies, сколько копий объекта будет создано
109-81
3. Отметьте флажок Duplicate Input Connections (Скопировать входящие соединения) - рис. 5.57. Этим действием вы соедините скопированный объект с узлом Input оригинала. Таким образом, при модификации узла Input оригинального объекта будут изменяться и его копии. 4. В поле Number of Copies введите нужное число копий (рис. 5.58).
146 Преобразование объектов и компонентов 5. Нажмите кнопку Duplicate. Создана копия объекта, к которой прикреплены узлы истории создания исходного объекта {рис. 5.59). Новый объект располагается непосредственно на оригинале. 6. Выберите инструмент Move и переместите скопированный объект на некоторое расстояние от оригинала. 7. В окне Channel Box выделите атрибут End Sweep (Конечная точка развертки) и перетащите указатель в рабочем окне, удерживая нажатой среднюю кнопку мыши. Вы увидите, что атрибут End Sweep одновременно изменяется в обоих объектах.
Для несложных операций копирована обычный инструмент Duplication слишком громоздок, так как содержит множество опций, которые надо настраивать или сбрасывать даже для обычного копирования. Если вы хотите создать копию и переместить ее по оси или просто скопировать объект два или три раза, вам будет более полезен инструмент Duplicate with Transform {Копировать с преобразованием).
Translate 2 0 ОЭ4 Rotate X О У0 Relate 10 Scale XM
Рис. 5.59. Скопировав объект с сохранением узла Input, можно продолжать изменять поверхности
Опции, копирования |147 ubdo
ctri+z
Redo
Z
Копирование объекта с простым перемещением
Reseat "Dupfcate wth Transform11 g Recent Cormiandi... Keys
>
DrtetB Delete by Туг»
*
Delete № by Type
*
1. Создайте сферу. 2. В меню Edit выберите пункт Duplicate with Transform (Копировать с преобразованием) - рис. 5.60.
Select ДИ Select Herarcriy Invwt Selection Select Al bv ТУИ •Junk Select Sets Pair* Selection Tool
3. Переместите скопированную сферу на несколько единиц по оси Z (рис. 5.61).
* • О
*#*•»** кшлтттш
Duplicate
Ctrl+d
в
jroup Ungroup
CtrH-g
О О *
Level of Deta.l Parent
p
О
Urparent
P
Э
Рис. 5.60 Выполните команды меню Edit LV Duplicate with Transform
4. В меню Edit выберите пункт Duplicate with Transform. Расстояние от новой сферы до второй равно расстоянию от второй сферы до начальной (рис. 5.62). 5. Нажмите клавиши Shift+d. Будет создана еще одна копия, расстояние от которой до предыдущей равно расстоянию между копией и оригиналом (рис. 5.63).
Рис. 5.61. Переместите копию сферы на такое расстояние, которое должно сохраняться между последующими копиями
Рис. 5.62. Скопируйте объект еще раз
Рис. 5.63. Каждая новая копия перемещается вдоль оси X на то же расстояние, что и начальная копия относительно оригинала
ГРУППИРОШЩ
ллоодомм
КШМШШШ
Группирование (grouping), наследование (parenting) и выравнивание (aligning) позволяют устанавливать определенные отношения между объектами, с помощью которых можно управлять моделями. Что* бы переместить по сцене ряд объектов одновременно, необходимо сгруппировать их. В этом случае они будут перемещаться как одно целое, что значительно экономит время, затрачиваемое на выделение, и способствует сохранению определенного расстояния между объектами.
6
Группирование, наследование и выравнивание 149 Наследование можно назвать дальним родственником группирования. Е^азница между этими двумя функциями сводится к следующему: наследование (рис. 6.1} вынуждает один объект повторять все движения другого (рис. 6.2), а объекты в группе могут действовать как независимо, гак и как единое целое. В этой главе рассматриваются различия между наследованием и группированием.
Рис. 6.1. Так в окне Hypergraph выглядят поверхности, связанные друг с другом отношениями наследования
Рис. 6.2. При перемещении сустава-родителя таким же образом передвигаются его дочерние суставы
Выравнивание объектов, поверхностей и кривых может оказаться сложной задачей, если вы пытаетесь выполнить его на глаз. В Maya есть специальные инструменты, которые позволяют без труда выравнивать любые объекты. Среди них можно назвать новые инструменты Align (Выровнять) и Snap Together (Связать друг с другом).
150
Группирование, наследование и выравнивание
Группирование и наследование Группирование двух или нескольких объектов связывает их дополнительным узлом, который называется group* - рис. 6.3. С его помощью можно одновременно изменять атрибуты двух объектов, например, синхронно перемещать их (вместо знака # в названии group* указывается номер узла группы). Даже если объекты сгруппированы, вы можете выбрать один объект и переместить его или произвести какое-либо действие, не затрагивая другие объекты группы. А если вы выделите узел группы, ваши действия будут влиять на все сгруппированные объекты так, как если бы они были единым целым {рис. 6.4). Наследованные объекты реагируют на преобразования не совсем так, как сгруппированные. Между наследованными объектами устанавливаются отношения предокпотомок. Когда ребенок держит за руку родителя, он должен идти за родителем, куда бы тот ни направился {по крайней мере, теоретически). Это утверждение верно и для трехмерной графики: объект-потомок, связанный отношением наследования с объектом-предком, должен всегда следовать за ним (рис. 6.5). При наследовании объектов дополнительного узла не создается. Какой объект будет предком, а какой потомком, программа определяет на основе очередности, в которой вы выделяете объекты.
Рис. 6.3. Верхний уз&л используется для изменения значений атрибутов, присущих всей группе, при этом текущие значения специфических атрибутов отдельных объектов не изменяются
Рис. 6.4. При повороте корневого узла все поверхности, входящие в группу, синхронно поворачиваются вокруг одного центра трансформаций
Рис. 6.5. Сфера слева является потомком сферы справа. Когда перемещается правая сфера, перемещается и левая
Группирование и наследование 151 Группирование двух или нескольких объектов 1. Выделите две или более поверхности, захватив их в рамку с помощью инструмента выделения (рис. 6.6), или щелкните по нескольким объектам, удерживая нажатой клавишу Shift. 2. В меню Edit выберите пункт Group (рис. 6.7}. Объекты сгруппированы, и создан дополнительный узел. Рис. 6.6. Чтобы выделить несколько поверхностей, достаточно захватить рамкой лишь часть нужной поверхности Edit
Mcxffly
create
Display
Undo
Redo
Repeat"Sphere" Recent Commands...
g
Keys Delete Delete by Type Delete Alt by Ту|эе Select Afl Invert Selection Select All by Type Quick Select Sets МШ Selection Tool Duplicate Cttt4d DupHeete with Transform D
Parent Unparent
j» f
Рис. 6.7. Чтобы сгруппировать объекты, выполните команду меню Edit ^ Group
Рис. Б.8. Верхний узел создается одновременно с группой. Он используется для управления узлами, находящимися под ним
3. В меню Window выберите пункт Нуpergraph (Гиперграф). Редактор откроется в новом окне. 4. Нажмите клавишу f, чтобы масштабировать вид в окне Hypergraph по выделенной области. Теперь узлов на один больше, чем объектов. Добавился узел группы с именем groupl (рис. 6.8). Чтобы синхронно перемещать сгруппиронанные объекты, выделите узел группы и переведите инструмент Pick mask в режим иерархии. А если необходимо переместить поверхность отдельно от группы, выделите узел поверхности и переведите инструмент Pick mask в режим выделения объектов,
152 Группирование, наследование и выравнивание Разгруппирование объекта 1. В окне Hypergraph выделите узел группы (рис. 6.9J. 2. В меню Edit выберите пункт Ungroup (Разгруппировать) - рис. 6.10. Объекты разгруппированы, а узел группы удален.
Рис. 6.9. По умолчанию имя узла группы - group#: где вместо знака # указывается порядковый номер группы
Когда объекты сгруппированы, их можно перемещать, поворачивать или масштабировать так, как если бы они были единым объектом. Узел группы в данном случае выполняет роль дополнительного центра трансформаций, который будет использоваться при вращении или масштабировании объектов. Когда объекты сгруппированы, центр трансформаций узла группы совпадает с началом координат. В дальнейшем эту точку можно переместить в любое место сцены, определив таким образом центр поворота или масштабирования.
ими
Перемещение, поворот и масштабирование группы 1. В окне Hypergraph выделите узел группы или щелкните по одному из объектов группы, установив инструмент Pick mask в режим иерархии &. 2. На панели инструментов выберите инструмент Rotate, Scale или Move или воспользуйтесь соответствующими «горячими» клавишами. 3. Чтобы перейти в режим редактирования центра трансформаций, нажмите клавишу Insert/Home.
Great*
Display
Undo Redo Repeat 'NURBS Cor*' Recent Commands...
Delete Delete by Type Delete Alt by Type
Wm
XZ -U-3CZ K¥
•
S*!*aAli Select Hierarchy Invert Selection Select Alt by Тура Quick Select Sets Paint $ЫйеВш тщй
KD О Duplicate wiMi Transform
UD
croup
KC о
Parent Unparem
Рис. 6.10. Чтобы разгруппировать объекты, выберите пункты меню Edit Ungroup
Группирование и наследование 153 4. Переместите центр трансформаций в то место сцены, вокруг которого вы будете вращать группу или относительно которого вы хотите ее масштабировать (рис. 6.11). Этот шаг можно пропустить, если требуется просто переместить группу. 5. Чтобы выйти из режима редактирования, нажмите клавишу Insert/Home.
Рис. 6.11. Центр трансформаций узла группы является центральной точкой для всей группы
6. Выполните перемещение, вращение или масштабирование группы. Для этого выберите нужную ось манипулятора (рис. 6.12) и перетащите указатель при помощи средней кнопки мыши влево или вправо по рабочему окну, чтобы изменить значение атрибутов по соответствующим осям. Чтобы переместить центр трансформаций в центр выделенной группы, выполните команды меню Modify => Center Pivot (Изменить ^> Центрировать центр трансформаций) - рис. 6.13. Create
Display
Win
Transformation Tools Reset Transformations Freeze Transformations Snap Align Objects Evaluate Nodes
Рис. 6.12. Группу можно перемещать, вращать или масштабировать как отдельный объект
Maka Live __ Prefix Hierarctiy Names.. tribute... Edit Attribute... Delete Attribute... Convert Script faint Tool Attribute Paint Too)
Рис. 6.13. Команда Modify => Center Pivot используется для быстрого переноса центра трансформаций группы в ее геометрическую середину
154 Группирование, наследование и выравнивание Перемещение объекта, входящего в группу 1. Переведите инструмент Pick mask в режим выделения объектов ^ и выделите объект, который требуется переместить. 2. На панели инструментов щелкните по кнопке инструмента Move или нажмите клавишу w. 3. Переместите объект. Для этого выберите любую ось манипулятора инструмента Move и перетащите указатель влево или вправо по рабочему окну при помощи средней кнопки мыши, чтобы изменить значение атрибута по соответствующей оси. Выделенный объект перемещается, а другие объекты группы остаются на месте (рис. 6.14).
Рис. 6.14. Сгруппированные объекты можно редактировать отдельно друг от друга, выделив только нужный объект
Вы можете выполнить те же действия, чтобы повернуть или масштабировать объект группы, не затрагивая остальные сгруппированные объекты. Если вы выбрали объект, входящий в группу, нажмите клавишу управления курсором, чтобы подняться вверх по иерархии и выделить узел группы. В качестве примера трехмерного наследования рассмотрим скелет двуногого существа. Начнем с руки. Она начинается в лопатке и идет вниз, соединяя плечо с верхней частью руки, далее с нижней частью, затем с запястьем, с ладонью и пальцами. Создается взаимосвязь, которая вынуждает пальцы следовать за остальной частью руки. Такое отношение называется отношением предок-потомок. В данном случае предок - верхняя часть руки, а ее потомок - нижняя часть, которая является предком запястья, а оно, в свою очередь, -
Рис. 6.15. Пальцы - потомки ладони, а она - потомок нижней части руки. Если двигается нижняя часть руки, все суставы и поверхности, находящиеся ниже сустава-предка, повторяют ее движения
Группирование и наследование 155 предком ладони. Всякий раз, когда двигается верхняя часть руки, все потомки, которые находятся под ней, также двигаются, имитируя движение всей руки (рис. 6.] 5), Взаимодействие частей скелета называется иерархией (рис. 6.16). Иерархия определяет, какой объект управляет другими. Порядок иерархии важен как при выделении, так и при перемещении объектов. Большое значение имеет порядок, в котором вы выделяете объекты, связывая их отношением наследования. Второй выделенный объект становится предком первого. После наследования потомок будет повторять движения предка. Рис. 6.16. Иерархия образуется наследованием одной кости другой
Создание отношения предок-потомок 1. Щелчком мыши выделите объект, который будет потомком. 2. Щелчком мыши выделите объект, который будет предком, удерживая нажатой клавишу Shift (рис. 6.17). 3. В меню Edit выберите пункт Parent (Наследовать) или нажмите клавишу р. Второй выделенный объект становится предком первого (рис. 6.18).
Рис. 6.17. Чтобы выделить несколько объектов, щелкните по ним, удерживая нажатой клавишу Shift
П
П
Рис. 6.18. Куб является предком цилиндра. В окне Hypergraph это показано с помощью соединительной линии
Когда объекты связываются отношением предок-потомок, корневого узла не создается, поэтому при управлении всей иерархией в качестве центральной точки используется центр трансформаций предка. Если выделено несколько объектов, все они становятся потомками последнего выделенного обьекта. Чтобы связать два объекта отношением предок-потомок, перетащите указатель мыши с помощью средней кнопки с потомка на родителя в окнах Hypergraph или Outliner.
156 Группирование, наследование и выравнивание Разрыв отношения предок-потомок 1. Выделите каждый элемент-потомок, который требуется отсоединить от предка, щелкнув но первому потомку, а затем нажав клавиш)' Shift и щелкнув по другим потомкам в окне Hypergraph или в рабочем окне, используя режим выделения объектов Pick mask. 2. Чтобы отсоединить потомка, в меню Edit выберите пункт Unparent или нажмите клавиши Shift+p (рис. 6.19). Объект исключается из иерархии и существует отдельно. Вы можете исключить выделенный объект из иерархии в окнах Hypergraph или Outliner и отсоединить его от остальной час™ иерархии с помощью средней кнопки мыши.
Modify
Create
Displiy
undo Redo Repeat "NURBS Cone" Recent Commands....
Win
O9IZ KY
Delete Deieia &f Type SeiettAII Select Hierarchy Invert Selection Select All by Type Quick Select Sets Paint Selection Tool Duplicate (Japtteate with Transfoin? Croup Ungroup L evel of Detail Patent
XD a *>o «G О
Я
Рис. 6.19. Чтобы разделить несколько наследованных поверхностей, выберите пункты меню Edit z> Unparent
Выравнивание и привязка объектов В реальном мире объекты соприкасаются и формируют другие объекты. Комната, например, образована несколькими примыкающими друг к другу стенами. Чтобы с необходимой точностью выстроить объекты и компоненты, можно воспользоваться инструментами выравнивания Maya (рис. 6.20). С их помощью вы сэкономите время, которое ушло бы на выравнивание объектов на глаз и выяснение, касаются ли объекты друг друга на самом деле. Инструменты выравнивания в Maya включают в себя инструменты Snap Align (Выравнивающая привязка) и Snap Together (Совместная привязка)1. Инструментом Snap В английском языке есть два термина Maya, которые на русский переводятся как «привязка», Первый — Snap, который рассматривается ниже, второй - Bind, описанный в 10 главе. — Прим. науч. ред.
Рис. 6.20. Вы можете выровнять точку одной поверхности с точкой другой поверхности. На рисунке выровнены две выделенные точки. Они находятся внутри квадрата
Выравнивание и привязка объектов pJ57 Align очень просто управлять, поскольку он целиком состоит из значков (рис. 6.21). А значит, нет никакого окна Options, в которое надо было бы заходить и устанавливать настройки. Инструмент Snap Align содержит множество опций выравнивания (например, выравнивание одного объекта по центру, верхней или нижней части другого производится простым нажатием на соответствующий значок). Инструмент Snap Together еще больше расширяет возможности этой операции, позволяя вращать и перемещать объект во время выравнивания (рис. 6.22).
Рис. 6.21. Графические элементы используются в качестве ярлыков для выполнения различных команд выравнивания
Привязки (snaps) - это сокращенные команды выравнивания, позволяющие быстро выровнять объекты или компоненты по линиям сетки, кривым, точкам или плоскостям вида. На рис. 6.23 представлено перемещение выделенного объекта на определенную линию сетки. Привязку можно использовать, чтобы убедиться, что компоненты кривых и поверхности на самом деле пересекаются с другими криными и поверхностями. Выполнение многих команд Maya требует, чтобы кривые и/или поверхности действительно соприкасались
Рис. 6.22. При вызове инструмента выравнивания на экране появляются стрелки, которые показывают, как команда выравнивания подействует на поверхности после нажатия клавиши Enter, завершающей выполнение команды
Рис. 6.23. С помощью привязки поверхности выравниваются вдоль линий сетки, кривых и точек
1584 Группирование, наследование и выравнивание друг с другом, иначе команда будет работать неправильно. Лучший способ убедиться, что выделенная точка касается нужной кривой, - выделить точку и с помощью привязки к кривой переместить ее на кривую. Привязка также помогает отобразить в окне проекции выделенные поверхности, которые находятся вне поля зрения. Для этого следует привязать выделенный объект к линии сетки или кривой, которая видна на экране.
ГЕЕ | Rmdawg j Qolh j FU& | Fui
Четыре вида привязки Рассмотрим четыре вида привязки Maya (рис. 6.24): • Snap to Grids (Привязка к сеткам} ^ (клавиша х). Привязывает контрольную вершину, центр трансформаций или вершину полигона к пересечению линий сетки. Если сначала включить :эту опцию, а потом нарисовать кривую, контрольные точки будут привязаны к пересечениям сетки (рис. 6.23);
Рис. 6.25. Привязка Snap to Curves выравнивает поверхность по кривой
• Snap to Curves (Привязка к кривым) ^ (клавиша с). Привязывает контрольную вершину, центр трансформаций или вершину полигона к отдельной кривой или кривой поверхности (рис. 6.25); • Snap to Points (Привязка к точкам) Align Tool. Выделенные цилиндры будут заключены в серый параллелепипед. На его ребрах располагаются значки-манипуляторы, которые используются для выравнивания объектов (рис. 6.43). 4. На параллелепипеде, окружающем объекты, щелкните по значку Щ, чтобы выровнять цилиндры (рис. 6.44). 5. Чтобы отменить выравнивание, нажмите клавишу г, затем щелкните по другому значку, чтобы посмотреть в действии еще один способ выравнивания, 6. Повторяйте предыдущий шаг до тех пор, пока вы не освоите все функции выравнивания.
Рис. 6.43. Серый параллелепипед, ограничивающий объекты, нужен лишь для наглядности. Чтобы запустить функцию выравнивания, щелкните по соответствующему значку Рис. 6.44. Заметьте, что на каждом значке изображено, по какой стороне или центру будут выравниваться объекты
166 Группирование, наследование и выравнивание Объекты выравниваются по последнему выделенному объекту, который окрашен в зеленый цвет.
Выравнивание одной точки по другой с помощью инструмента Point-to-Point Snap Align 1. Создайте цилиндр и конус. 2. Выделите объекты и нажмите клавишу F8. 3. Выделите одну контрольную вершину на цилиндре, затем нажмите клавишу Shift и выделите вторую контрольную вершину на конусе (рис. 6.45).
Рис. 6.45. Вы можетз выделить любую редактирующую точку или контрольную вершину, которую нужно выровнять с любой редактирующей точкой или контролвной вершиной другой поверхности
4. В меню Modify щелкните по значку рядом с пунктом Snap Align Objects ^> Point to Point. Цилиндр перемещается и выравнивается с конусом. Две выделенные точки точно совмещены (см. рис. 6.46), Чтобы выровнять только точки, а не весь объект, вместо инструмента Point-to-Point Snap Align воспользуйтесь инструментом Point Snap (см. ранее в этой главе).
Выравнивание двух или трех точек с двумя или тремя точками при помощи инструментов 2/3 Point-to-Point Snap Align 1. Создайте цилиндр и конус. 2. Выделите объекты и нажмите клавишу F8. 3. Выделите две (или три) контрольные вершины на цилиндре, затем нажмите клавишу Shift и выделите две (или три) контрольные вершины на конусе (рис. 6.47).
Рис. 6.4Б. Две выделенные точки как будто бы превратились в одну, но на самом деле они очень точно совмещены друг с другом
Выравнивание и привязка объектов 167
Рис. Б.47. Выделенные точки выравниваются с другими выделенными точками настолько близко, насколько возможно, но форма поверхности при этом не изменится Create
Display
Transformation Tools Reset Transformations Freeze Transformations
Window
EdnCm1...
Surfaces
f'V- nufbiConel
Evaluate Nodes Make Live Center Pivot Prefix Hierarchy Names..
3 Points to Э Petals Align Objects
О О
Align Tool
Рис, 6.48. В выпадающем меню Snap Align Objects вы найдете почти все команды выравнивания
Рис. 6.49. Точки цилиндра выравниваются в соответствии с точками, выбранными на поверхности конуса
4. Если вы выбрали две контрольные вершины на каждом объекте, в меню Modify щелкните по значку рядом с Snap Align Objects ^> 2 Points to 2 Points. Если вы выбрали три точки на каждом объекте, щелкните по значку рядом с пунктом Snap Align Objects => 3 Points to 3 Points (рис. 6.48). Весь объект с выделенными первыми точками (в данном случае это цилиндр) переместится и выровняется с выделенными точками второго объекта (конуса). Если между точками на каждом из объектов разное расстояние, то они могут не разместиться точно друг на друге (рис. 6.49).
и пошиости ниш С помощью кривых NURBS можно создать практически любой объект: средневекового рыцаря, пришельца с другой планеты, механизм или просто любой выдуманный вами объект. Поверхности NURBS в основном используются для органического моделирования, поскольку создаваемые ими волнистые закругленные формы прекрасно подходят для моделирования деревьев, людей и животных. Читатели, имеющие некоторый опыт работы в других программах, использующих кривые Безье (например, Adobe Illustrator), легко освоят и построение кривых NURBS. Хотя кривые NURBS и отличаются от кривых Безье, но создаются и редактируются они похожим образом. Кривые Безье и NURBS представляют собой искривленные линии, форму которых можно изменять, перемещая точки, расположенные вдоль кривой (начальное положение точек определяется при создании кривой). Кривые NURBS можно использовать для моделирования каркаса конечной поверхности, для очерчивания контура, при вращении которого вокруг определенной оси создается поверхность, а также для точной пастройки поверхности (рис. 7.1).
7
Рис. 7.1. Вы можете редактировать поверхность, полученную вращением контура, изменения кривую NURBS, которая использовалась для создания контура
Объекты NURBS
169
Объекты NURBS
Контрольные точки
Объекты NURBS позволяют очень точно управлять конечной поверхностью. Их можно разделить на два вида: кривые и поверхности.
Огибающие
Редактирующие точки
Рис. 7.2. Компоненты IMURBS позволяют быстро изменять вид кривой или поверхности
Рис. 7.3. Компоненты поверхности NURBS используются для управления видом поверхности
У кривых NURBS существует три основных компонента: контрольные вершины (СУ), редактирующие точки (edit points) и огибающие (hulls) - рис. 7.2. Они используются для создания и редактирования кривых различными способами. Ближе познакомившись с созданием кривых NURBS, вы, возможно, выберете наиболее удобный для себя способ, который впоследствии станет для вас основным методом редактирования. Помимо контрольных вершин, редактирующих точек и огибающих, у поверхностей NURBS есть и другие, более сложные компоненты: нормали к поверхности (surface normals), центры питчей (patch centers) и начала поверхности (surface origins) рис. 7.3. Любую поверхность NURBS, созданную из кривой (например, поверхность вращения}, можно редактировать, внося изменения в компоненты начальной кривой или непосредственно в компоненты поверхности. Если поверхность создана из одной или более кривых, ее связь с этой кривой сохраняется посредством истории создания. Таким образом, изменяя кривую, вы также редактируете и поверхность.
170 Кривые и поверхности NURBS Каждый компонент NURBS (редактирующие точки, контрольные вершины и т.д.) можно отображать и редактировать отдельно (на рис. 7.4 показаны редактирующие точки) или вместе с другими компонентами (на рис. 7.5 изображены редактирующие точки и огибающие). Кривые важная составляющая NURBS-моделирования, потому что с их помощью можно создавать и редактировать поверхности. Данная глава целиком посвящена этой интересной теме.
Создание кривых NURBS Изучив процесс создания и редактирования кривых, вы поймете, как в полной мере использовать инструменты моделирования Maya. Большое количество редактирующих точек позволяет с ювелирной точностью управлять формой и размещением кривых NURBS. Кривые часто используют для создания каркаса поверхности. Затем необходимо натянуть на каркас оболочку (рис. 7.6), чтобы закончить построение поверхности. Создать конечную поверхность можно с помощью таких команд Maya, как яофтинг (lofting), выдавливание (extruding) и вращение (revolving) - все они будут подробно рассмотрены в этой главе.
Рис. 7.4. Чтобы упростить выделение и редактирование, необходимо отобразить только редактирующие точки поверхности. Любой компонент можно выделить, щелкнув по его значку. В данном случае используются пиктограммы с изображением кростика
Рис. 7.5. Maya позволяет отображать и скрывать столько компонентов, сколько необходимо на данном этапе работы. Это помогает сузить возможную область выделения и в то же время иметь представление о том, как выглядят другие компоненты объекга
Создание кривых NURBS
171
Анатомия кривой У каждой кривой NURBS есть соответствующее направление, которое определяется порядком создания контрольных верптин. Направление кривой имеет .шачение при определении вида конечной поверхности, созданной на ее основе. Если вы не замечаете, в каком направлении строите кривую, то при создании конечной поверхности можете получить неожиданные результаты. Кривые, ориентированные в направлении, противоположном нужному, могут скрутить конечную поверхность и обратить ее нормали.
Рис. 7.6. Кривые, которые использовались для создания каркаса (вверху), и те же кривые с натянутой на них оболочкой (внизу) Вторая точка
Направление кривой определяется первой и второй контрольными вершинами, созданными при построении кривой. Первая контрольная вершина, или начальная точка (start point), обозначается маленьким квадратом. Вторая контрольная вершина имеет вид буквы U. Начальная точка, за которой следует вершина, помеченная буквой U, указывает направление кривой; таким же образом определяется направление U любой поверхности, созданной из кривой (рис. 7.7). Кривые NURBS в основном используются в моделировании, поэтому при визуализации сцены они не отображаются.
Направление
Начальная точка
Рис. 7.7. Направление U кривой определяется первой и второй контрольными вершинами
1721 Кривые и поверхности NURBS У каждой кривой есть следующие компоненты (рис. 7.8):
Редактирующая точка Точка кривой
Направление
• контрольные вершины (control vertices) размещаются на небольшом расстоянии от кривой и чаще всего используются при редактировании формы кривой; • редактирующие точки, или изломы (edit points (knots)) размещаются прямо на кривой и обозначаются маленьким значком в виде буквы х. Это еще одно средство редактирования формы кривой; •
огибающие (hulls) прямые соединяют контрольные вершины. Отображение огибающих помогает выяснить, как связаны между собой контрольные вершины. Щелкнув по огибающей, вы выделите весь ряд расположенных на ней контрольных вершин;
• сегменты (spans) представляют собой область между двумя редактирующими точками. Каждый раз при создании редактирующей точки добавляется сегмент. Сегменты нельзя изменять непосредственно (как редактирующие точки), но они отображают результаты редактирования. Сегменты используются при создании и перестройке кривых и поверхностей. Чем больше сегментов вы добавите, перестраивая поверхность, тем больше будет создано редактирующих точек. Однако поверхность, имеющая много сегментов, становится более детализированной и трудной для расчетов; • точка кривой {curve point) представляет собой произвольную точку, которая используется для того, чтобы отсоединить кривую от другого объекта или выполнить выравнивание. Она может находиться в любом месте кривой;
Огибающая
Сегмент
Начальная точка
Рис. 7.8. На рисунке показаны все компоненты кривой NURBS
Создание кривых NURBS 173 •
начальная тонка {start point) - это первая созданная контрольная вершина кривой, которая обозначается маленьким квадратом;
•
направление кривой (curve direction) определяется первой и второй контрольными вершинами, созданными для этой кривой.
Создание кривых с различными степенями Рис. 7.9. Степень кривой, равная единице, определяет линейную кривую и линейную поверхность
Рис. 7.10. Степень кривой, равная трем, определяет гладкую кривую, для создания которой достаточно четырех контрольных вершин
У каждой кривой есть определенная степень; чем выше степень, тем больше гладкость кривой. Степень кривой может равняться 1, 2, 3, 5 или 7. Кривая со степенью 1 -линейная, и чтобы ее определить, нужно всего две точки (рис. 7.9}. Линейные кривые и поверхности характеризуются прямыми линиями и острыми углами. Степень кривой, равная трем, создаст гладкую кривую, для описания которой будет использовано несколько контрольных вершин (рис. 7.10). Кривая со степенью 3 - самая универсальная, так как для ее создания нужно всего четыре тачки, и она достаточно плавная для моделирования поверхностей высокого качества. Разработчики автомобилей часто пользуются степенями выше 5, так как при производстве машин нужна высокая точность. Для анимации же степени, равной трем, более чем достаточно, Как вы уже поняли, контрольных вершин должно быть на одну больше, чем степень кривой. Например, для кривой со степенью, равной трем, необходимо создать четыре контрольных вершины {рис. 7.10),
1741 Кривые и поверхности NURBS а для кривой со степенью 7 - восемь контрольных вершин, таким образом поверхность становится более трудной для редактирования и расчета (рис. 7.11). Именно поэтому наиболее универсальной является степень, равная трем или пяти,
Создание профильных кривых Вы можете создавать множество различных объектов, рисуя вначале контурные кривые по форме профиля объекта. Затем вращением этой профильной кривой создается конечная поверхность (рис. 7.12). Кроме того, профильную кривую можно затем изменять, чтобы усовершенствовать форму объекта уже после создания конечной поверхности. Это позволяет делать история создания, при помощи которой профильная кривая соединена с конечной поверхностью (рис. 7.13). Если вы рисуете профильную кривую для вазы, стакана, кувшина или любого другого объекта, у которого есть стенки определенной толщины, нужно наряду с профилем внешней поверхности нарисовать
Рис. 7.11. На рисунке показана кривая со степенью, равной семи, а это значит, что для ее определения необходимо восемь контрольных вершин
Рис. 7.12. Эта симпатичная ваза была создана вращением единственной кривой
Рис. 7.13. Перемещая точку кривой, с помощью которой была создана поверхность вращения, вы можете интерактивно изменять форму объекта
Создание кривых NURBS 175
Профиль внутренней — части вазы
Рис. 7.14. Рисуя профильную кривую, не забудьте добавить внутреннюю часть поверхности, чтобы определить толщину конечного объекта
и профиль внутренней (рис. 7.14). Если этого не сделать, стенки сосуда будут толщиной с бумагу, что выглядит не слишком естественно. Поскольку большинство реальных объектов имеют глубину или размерность, нужно воссоздать эти параметры и в Maya. Толщина стенок стакана определяется тем, как вы нарисуете профильную кривую. Обычно кривую создают при помощи одного из трех инструментов: CV Curve (Кривая по контрольным вершинам), ЕР Curve (Кривая по редактирующим точкам) или Pencil Curve (Карандашная кривая).
Создание кривой при помощи инструмента CV Curve 1. В меню Create выберите пункт CV Curve (Кривая по контрольным вершинам). 2. Щелкните в нескольких точках вида сверху. Каждое нажатие мыши создаст контрольную вершину, а после четвертого нажатия появится кривая (рис. 7.15). Рис. 7.15. Эта кривая построена из точек, которые созданы с помощью инструмента CV Curve
3. Нажмите клавишу Enter, чтобы завершить создание кривой. Кривая подсвечивается - это значит, что она выделена.
Создание кривой при помощи инструмента ЕР Curve 1. В меню Create выберите пункт ЕР Curve (Кривая по редактирующим точкам).
Рис. 7.16. Эта кривая была создана с помощью инструмента ЕР Tool Curve
2. Щелкните в нескольких местах вида сверху. Как только вы создадите вторую точку, на экране появится кривая, форма которой будет определяться по мере добавления каждой новой точки (рис. 7.16). 3. Нажмите клавишу Enter, чтобы завершить создание кривой.
17ВI Кривые и поверхности NURBS Создание кривой при помощи инструмента Pencil Curve 1. В меню Create выберите пункт Pencil Curve. 2. Чтобы нарисовать линию, щелкните на виде сверху и перетащите указатель мыши. Создание кривой будет завершено, как только вы отпустите кнопку мыши. Инструмент Pencil Curve - менее эффективный способ создания кривой, потому что в результате получается намного больше точек, чем нужно, чтобы описать форму (рис. 7,17).
Рис. 7.17. Нижняя кривая была создана инструментом Pencil Curve
Как говорилось ранее, у каждой кривой есть направление, которое называется направлением. U. Иногда требуется изменить его на противоположное, если из кривых получаются некорректные поверхности (рис. 7.18).
Обращение направления кривой 1. Выберите кривую в режиме выделения объектов. 2. В меню Edit Curves (Редактировать кривые} выберите пункт Reverse Curve Direction (Обратить направление кривой) - рис. 7.19,
Рис. 7.18. Неправильно направленная кривая может вызвать ненужные проблемы. Самый лучший результат достигается при одинаковом направлении всех кривых одной поверхности j Edit Curves
surfaces
Edit \URB
Duplicate Surface Cirves
я
Attach Curves Detach Cur VP s Align Curues Open/Close Curves Move Seam cut Curve Intersect Curves Insert Knot Extend
offset
Re verse Curve nreotion
Рис. 7.19. Чтобы изменить направление кривой, выполните команды меню Edit Curves ^> Reverse Curve Direction
Создание кривых NURBS
177
3. Чтобы просмотреть новое направление кривой в режиме выделения компонентов, нажмите клавишу F8 (рис. 7.20).
Двумерные скругления
Рис. 7.20. Верхняя кривая направлена в одну сторону, а нижняя - в противоположную
Рис. 7.21. Двумерное округление прекрасно подходит для добавления сглаженных углов в набор кривых
12Э-81
Скругление (fillet) - это сглаженный угол соединения, который образуют две кривые или поверхности. Чтобы соединить цугами несколько кривых, можно создавать двумерные скругления. Иногда проще построить две кривые и затем связать их дугой, чем нарисовать одну кривую с необходимым скруглением. Примером может служить создание закругления вне двух перпендикулярных кривых, как на рис. 7.21.
1781 Кривые и поверхности NURBS Создание двумерного округления 1. Создайте две кривые, которые будете соединять дугой (рис. 7.22). 2. Правой кнопкой мыши щелкните но первой кривой и в контекстном меню выберите пункт Curve Point (рис. 7.23}. 3. Щелкните по первой кривой и перетащите указатель туда, где скругление должно образовать дугу (рис. 7.24).
Рис. 7.23. Щелкните по кривой правой кнопкой мыши, чтобы вызвать контекстное меню. С его помощью очень удобно выбирать тот или иной тип компонента
4. Правой кнопкой мыши щелкните по второй кривой и в контекстном меню выберите пункт Curve Point, 5. Удерживая нажатой клавишу Shift, щелкните по второй кривой и перетащите точку кривой туда, где скругление должно образовать дугу (рис. 7.25). 6. В меню Edit Curves выберите пункт Curve Fillet (Скругление кривых). Между двумя точками кривых создана дуга (рис. 7.26).
Рис. 7.24. Щелкнете по точке кривой и перетащите ее в то место, из которого вы хотите начать дугу
Рис. 7.22. Две кривые пересекаются
Рис. 7.25. Две точки кривой определяют начальную и конечную точки дуги
Создание кривых NURBS 179
Размыкание и замыкание кривых Кривая, начало и конец которой не совпадают, называется незамкнутой (рис. 7.27). Многие команды Maya, примененные к незамкнутым кривым, будут выполняться некорректно, поэтому кривые для таких команд нужно замыкать. У замкнутой кривой начальная и конечная точка совпадают, что делает ее непрерывной (рис. 7.28).
Размыкание и замыкание кривой
Рис. 7.26. Между двумя точками, выделенными на каждой кривой, создана дуга
Рис. 7.27. Неполная окружность является незамкнутой кривой
В меню Edit выберите пункт Open/Close Curves (Разомкнуть/замкнуть кривую) рис. 7.29. Незамкнутая кривая превратится в замкнутую, а замкнутая разомкнется.
Рис. 7.28. Начальная и конечная точки замкнутой кривой совпадают
Edit Curves
surfaces
Edit NURBS
Delicate Surface Curues
Э
Attach Ciewes Detadi curves ABgn curves Open.'Close curves
Рис. 7.29. Команда Open/Close Curves размыкает замкнутую кривую и выполняет обратное действие по отношению к незамкнутой
1801 Кривые и поверхности NURBS Разбиение кривой 1. Выделите кривую при помощи инструмента Pick mask, переведенного в режим Component: Farm Points (Компонент: параметрические точки) *. 2. Выделите значок х редактирующей точки в том месте, где вы хотите разбить кривую (рис. 7.30). 3. В меню Edit Curves выберите пункт Detach Curves. Теперь кривая разбита на две части (рис. 7.31}, Если в диалоговом окне Detach Curve Options включена опция Keep Originals (Сохранить оригиналы), после отсоединения вы получите три кривые: начальную и две отсоединенных. Чтобы автоматически удалить начальную кривую, снимите флажок Keep Originals перед тем, как рассоединить кривую (см. раздел «Функция Keep Originals»}.
Рис. 7.30. Редактирующая точка обозначается перекрестием. Ест она выделена, то ее можно использовать как точку разрыва кривой
Функция Keep Originals Большинство команд для работы с кривыми и поверхностями имеют функцию Keep Originals (Сохранить оригиналы). Если вы перестраиваете кривую с помощью такой команды, как Detach, опция Keep Originals позволит сохранить исходную кривую. Помните, что исходная кривая иди поверхность будет располагаться иод новыми кривыми и поверхностями, поэтому ее можно не замегить,
Рис. 7.31. После разделения в редактирующей точке созданы две кривые
Создание поверхностей из кривых 181
Создание поверхностей из кривых
Рис. 7.32. Профильная кривая определяет контур объекта, использованный при вращении Surfaces
Й
Loft olanar
О О
Extrude
3
Biraif
2. Выделите кривую в режиме выделения объектов.
'
Boundary Square
Рис. 7.33. Чтобы открыть окно Revolve Options, в меню Surfaces щелкните по значку рядом с пунктом Revolve
Bevel Bevel Plus
e>_§_
ions
•
*v
"" O*
10000
O.OOOO
iOOCO)
JOOOOC
6 f'-
e p.... Sur'ace LiEyf.j
Создание вазы вращением кривой 1. На виде спереди нарисуйте кривую, создав «профиль» вазы, как на рис. 7.32.
Ed* NURBS
Revolve
В Maya есть несколько команд, которые используются для превращения кривых в поверхности: Revolve (Вращать), Loft (Создание по сечениям), Planar (Делать плоским), Extrude (Выдавливание), Birail (Строить на двух направляющих) и Boundary (Граница).
О Cubic
Sun SnrttD *"#
3. В меню Surfaces (Поверхности) щелкните по значку рядом с пунктом Revolve (рис. 7.33). Откроется диалоговое окно Revolve Options. 4. Выделите ось, вокруг которой будете вращать кривую (рис. 7.34), В данном примере используется ось Y, 5. Чтобы создать поверхность вазы, нажмите кнопку Revolve. Если результат получился неожиданным, возможно, неправильно была выбрана ось вращения, 6. Чтобы улучшить сглаживание и увидеть поверхность во всех деталях, нажмите клавишу 3 (рис. 7.35).
Рис. 7.34. Ось вращения имеет большое значение для вида конечной поверхности. Выберите ось, которая проходит через середину конечной поверхности Рис. 7.35. Увеличение гладкости поверхности помогает выяснить, где реально находится поверхность вращения
182 Кривые и поверхности NURBS Чтобы создать поверхность вращения с разверткой менее 360°, в окне Revolve Options настройте опции Start Sweep Angle (Начальная точка развертки) и End Sweep Angle (Конечная точка развертки). Чтобы интерактивно изменить форму поверхности вращения, переопределив угол поворота вокруг оси. воспользуйтесь инструментом Show Manipulator. Один из лучших способов создать поверхность из нескольких кривых - это воспользоваться командой Loft. С ее помощью создается поверхность, которая вытягивается от одной выделенной кривой к следующей до тех пор, пока все кривые не будут обтянуты оболочкой. Каждая из изоиарм конечной поверхности выводится исходя из размещения редактирующей точки на начальной кривой. По общепринятым правилам, на каждой кривой должно быть одинаковое количество редактирующих точек.
Рис. 7.36. Каждая кривая, вдоль которой будет производиться лофтинг, определяв" контур конечной поверхности
Лофтинг вдоль нескольких кривых 1. Создайте две или несколько кривых, из которых будет строиться поверхность (рис. 7.36). 2. Удерживая нажатой клавишу Shift, щелкните по каждой кривой в том порядке, в котором требуется произвести лофтинг поверхности. Порядок выделения кривых очень важен. Поверхность начнется в первой выделенной кривой и закроет все дополнительные кривые в порядке их выделения. 3. Закончив выделение кривых, выполните команды меню Surfaces "=> Loft, чтобы обтянуть кривые оболочкой (рис. 7.37).
Рис. 7.37. Поверхность, созданная методом лофтинга, связана с исходными кривыми при помощи истории создания, поэтому ее можно редактировать, используя зти кривые
Создание поверхностей из кривых 183 Новая поверхность отображается при низком сглаживании, поэтому кажется, что она не полностью касается кривых, использованных при ее создании. Чтобы просмотреть поверхность в режиме высокого сглаживания, выделите ее и нажмите клавишу 3. Рис. 7,38. Для выдавливания можно использовать кривые любой формы. Например, если требуется получить поверхность цилиндрической формы, возьмите замкнутую кривую
С помощью команды Extrude (Выдавливание) поверхность создается протаскиванием одной кривой (профиля) вдоль другой (пути). Она позволяет цобавить глубину в текстовый объект и довольно часто используется для создания длинных цилиндрических объектов, например, проводов питания.
Выдавливание кривой
Рис. 7.39. Вторая кривая, созданная для выдавливания, используется для определения пути и длины поверхности
1. Создайте профильную кривую, определяющую сечение конечной выдавленной поверхности. Например, если требуется получить поверхность цилиндрической формы, создайте окружность (рис. 7.38). 2. Начиная с уже созданной кривой, постройте с помощью контрольных точек кривую, которая определит длину конечной поверхности (рис. 7.39). Эта линия называется кривой пути (path curve}. 3. Выделите окружность и кривую пути, удерживая нажатой клавишу Shift. 4. В меню Surfaces выберите пункт Extrude, чтобы протащить профильную кривую вдоль кривой пути. На экране появится новая поверхность (рис. 7.40).
Рис. 7.40. Поверхность, созданная выдавливанием, следует сечению профильной кривой
184 Кривые и поверхности NURBS По умолчанию новая поверхность начинается под углом профильной кривой и копирует ее углы. Если профильная кривая перпендикулярна кривой пути, выдавленная поверхность просто следует кривой пути. Чтобы проигнорировать угол профильной кривой и чтобы кривая следовала кривой пути, в окне Extrude Options поставьте флажок At Path.
Команда Make Planar (Создать плоскую поверхность} используется для формирования плоской поверхности из кривых. В качестве примера можно рассмотреть создание плоской поверхности гитары (той части, в которой есть отверстие) -рис. 7.41. Контур корпуса гитары можно построить с помощью кривой, а затем воспользоваться командой Make Planar и завершить создание плоской поверхности,
Рис. 7.41. Команда IVIake Planar позволяет создать поверхность из лю()ой замкнутой кривой, лежащей в одной плоскости
Создание плоской поверхности 1. Создайте замкнутую кривую, все контрольные вершины которой лежат в одной плоскости (рис. 7.42). 2. В меню Surfaces выберите пункт Planar (Плоская поверхность). Из кривой создана пленарная поверхность (рис. 7.43).
Рис. 7.42. Эта замкнутая кривая определит контур поверхности. Воспользуйтесь привязкой к сетке, чтобы убедиться, что все точки кривой лежат в одной плоскости
Чтобы команда Planar выполнялась корректно, кривая должна быть замкнутой или самопересекающейся, а все контрольные вершины должны лежать в одной плоскости. Чтобы удовлетворить этим условиям, рекомендуется привязать каждую контрольную точку к плоскости сетки.
Рис. 7.43. Из кривой, которой был очерчен контур будущей поверхности, создана плоская поверхность
Создание поверхностей из кривых И 85
Рис. 7.44. Корпус лодки можно создать с помощью нескольких профильных и двух направляющих кривых
Инструмент Birail (Построить на двух направляющих) похож на Extrude, однако вместо одной кривой пути и одной профильной кривой, в нем есть две кривые пути (направляющие) и любое число профильных кривых. ]3 качестве примера рассмотрим построение корпуса лодки. Две кривые пути определяю! контур корпуса, а профильные кривые - его глубину и форму (рис. 7.44).
Создание поверхности на двух направляющих 1. Нарисуйте две кривые, которые будут использоваться в качестве направляющих поверхности (рис. 7.45).
Рис. 7.45. В качестве направляющих всегда используются две кривые Направляющие кривые
Профильная кривая
2. Создайте новую кривую. Удерживая нажатой клавишу с, щелкните на направляющей кривой и перетащите указатель таким образом, чтобы привязать ее к первой и последней точкам направляющих кривых (рис. 7.46). Чтобы инструмент Birail работал корректно, кривые должны соприкасаться друг с другом, а привязка гарантирует, что профильная кривая касается обеих направляющих. 3. В меню Surfaces выберите пункты Birail => Birail I Tool (рис. 7.47). Если у вас две профильные кривые, воспользуйтесь инструментом Birail 2 Tool. Если же вы построили несколько профильных кривых, выберите инструмент Birail 3+.
Рис. 7.46. Чтобы команда выполнялась корректно, необходимо осуществить привязку к кривой: концы каждой профильной кривой привязать к направляющим
Si*feces
Edit NURB
Revolve Loft Planar Extrude Boundary Square
Bran 2 Tool №813+ Tool
Рис. 7.47. В меню Surfaces выберите пункты Birail о Birail 1 Tool
186 Кривые и поверхности NURBS 4. Щелкните по профильным кривым, а затем по направляющим (рис. 7.48). На экране отобразится поверхность, созданная на двух направляющих. Для выполнения команды Boundary (Граница) потребуются три или четыре кривые, которые пересекаются или соединяются концами. Рассмотрим пример создания подобной поверхности. Есть три поверхности, соединенные в углах, между которыми с помощью трех ребер требуется создать закругленный угол (рис. 7.49).
Рис. 7.48. Поверхность создана из трех кривых с помощью инструмента Birail
Создание поверхности на основе границ 1. Нарисуйте три или четыре кривые с пересекающимися концами (рис. 7.50). При этом рекомендуется привязать первую и последнюю контрольные вершины каждой кривой к другим кривым. 2. Выделите все кривые, создающие ограниченную область (рис. 7.51). 3. В меню Surfaces выберите пункт Boundary. На экране отобразится поверхность, созданная на основе границ (см. рис. 7.52).
Рис. 7.49. Инструмент Boundary идеально подходит для заполнения разрыва между этими поверхностями
Рис. 7.50. Чтобы команда Boundary выполнялась корректно, рекомендуется использовать привязку к кривой каждой конечной точки
Создание поверхностей из кривых 187 Создание скошенного текста 1. Б меню Create щелкните но значку рядом с пунктом Text. Появится диалоговое окно Text Curves Options (Опции текста в кривых). 2. В ноле Text введите текст. 3. Выберите шрифт текста. Рис. 7.51. Выделите кривые и изопармы, к которым будет применяться команда Boundary
4. В поле Curves поставьте переключатель Туре. 5. Нажмите кнопку Create (рис. 7.53). 6. В меню Surfaces выберите пункт Bevel (рис. 7.54). Текст можно редактировать с помощью узла Inputs после создания или R диалоговом окне Text Curves Options до создания (рис. 7.55). В окне Channel Box можно настроить ширину и глубину выдавливания в узле скоса Inputs.
Рис. 7.52. По трем кривым создана поверхность £* Text Curves Options Edit Нф
Рис. 7.53. В окне Text Curves Options определите параметры Text, Font и Type, а затем нажмите кнопку Create
ИНЯНН Edit N Revolve Loft Planar
О О О
Extrude Birail
О »
Boundary
О
* Рис. 7.54. В меню Surfaces выберите пункт Bevel
Рис. 7.55. Кривые, которые описывают буквы, превратились в скошенные поверхности
1881 Кривые и поверхности NURBS Чтобы нарисовать кривую непосредственно на поверхности, последнюю необходимо активировать. Если поверхность активна (live), то кривую можно создавать и редактировать непосредственно на ней.
Активирование поверхности 1. Выделите поверхность, которую требуется активировать (рис. 7.56). 2. В меню Modify (Изменить) выберите пункт Make Live (Активировать) или нажмите на кнопку &. Каркас активированной поверхности станет зеленым (рис. 7.57). Чтобы дезактивировать активную поверхность, в меню Modify выберите пункт Make Not Live.
Рисование кривой на активной поверхности
Рис. 7.56. Сферу активировали, чтобы нарисовать кривую прямо на ней. Активной можно сделать любую поверхность Зеленый
1. Активируйте поверхность. 2. В меню Create выберите пункт CV Curve Tool (рис. 7.58). 3. Щелкните в тех точках поверхности, где вы хотите создать кривую (рис. 7.59). 4. Нажмите клавишу Enter, чтобы завершить создание кривой. На поверхности создана кривая. 5. В меню Modify выберите пункт Make Not Live, чтобы дезактивировать поверхность (рис. 7.60). С помощью инструмента Move кривую можно перемещать по поверхности в направлении U или V.
Рис. 7.57. Если каякас поверхности становится зеленым, это означает, что поверхность активна
Создание поверхностей из кривых Create
Display
Проецирование кривой позволяет создать на выделенной поверхности новую кривую. Представьте, что изображение кривой проецируется на объект проектором слайдов, Форма объекта может исказить изображение кривой. Таким же образом и кривая, полученная в результате проецирования на поверхность объекта, в какой-то степени деформируется.
Window
NURBS Primitives Polygon Primitives subdlv Primitives Volume Primitives Cameras CV Curve foot ЁР Curve Tool t*encff Curve Tool
Рис. 7.58. В меню Create выберите пункт CV Curve Tool
В качестве примера рассмотрим проецирование на модель тыквы двух кривых, которые определяют форму глаз. Для этого требуется нарисовать на виде спереди глаза, которые будут вырезаны на тыкве, и проецировать эти кривые на объект (рис. 7.6]). Затем можно воспользоваться функцией вырезания, чтобы вырезать форму, созданную спроецированной кривой, из поверхности.
Рис. 7.59. Рекомендуется поворачивать вид вокруг поверхности, чтобы осмотреть без искажений перспективы место, где вы хотите поместить контрольные вершины I МосИу
create
Display
Wridow
Transformation Tools Reset TransfratTKrtfans Freeze Transformations Snap Align Objects Enable Nodes Make Not Live Center Muot Prefix hierarchy Names.,,
Рис. 7.60. В меню Modify выберите пункт Make not Live, чтобы вернуться в обычный режим
Рис. 7.Б1. Проецирование кривых на поверхность позволяет определить контур, по которому впоследствии будет вырезана часть поверхности
190| Кривые и поверхности NURBS Проецирование кривой на поверхность 1. Создайте поверхность, на которую будет проецироваться кривая, например, сферу. 2. На виде спереди создайте кривую, которую нужно проецировать на поверхность. В данном примере используется окружность (рис. 7.62). 3. Выделите кривую и поверхность (см. рис. 7.63). 4. В меню Edit NURBS (Редактировать NURBS) вида спереди выберите пункт Project Curve on Surface (Проецировать кривую на поверхность) - рис, 7.64. Кривая спроецирована на обе части поверхности сферы - переднюю и заднюю (рис. 7.65).
Рис. 7.63. Чтобы проецирование выполнялось корректно, необходимо выделить и поверхность, и кривую Edit MURES
Polygons
Edit Pol
Duplicate NURBS Patches
Вырезание отверстия в поверхности 1. Выполните действия, описанные в предыдущем примере. 2. В меню Edit выберите пункт Trim Tool (Инструмент вырезания).
Intersect Surfaces Trim Tool Untrim Surfaces
О О П
Рис. 7.64. Угол, под которым проецируется кривая, зависит от того, is каком окне проекции осуществляется процедура
ч
Рис. 7.62. Окружность будет спроецирована на поверхность сферы
Рис. 7.65. Кривая проецируется на переднюю и заднюю стороны объекта
Создание поверхностей из кривых 191 3. Щелкните по сфере. Объект становится прозрачным, а линии - белыми. Это означает, что активирован инструмент Trim (рис. 7.66). 4. Щелчком мыши определите ту часть сферы, из которой будет вырезаться кусок (если щелкнуть по вырезаемой поверхности, результат может получиться неожиданным). Желтый ромб показывает область, которую вы хотите сохранить (рис. 7.67).
Рис. 7.66. Объект становится прозрачным, и каждая область, которая будет подвергнута вырезанию, заполняется сеткой
5. Чтобы вырезать поверхность, нажмите клавишу Enter. Кривая была спроецирована на обе стороны сферы, поэтому в поверхности теперь два отверсшя (рис. 7.68).
п
Рис. 7.67. Желтый ромб показывает область, которая будет сохранена
Рис. 7.68. На месте спроецированных кривых образовались два отверстия
Вы можете сохранить любую область поверхности, к которой применялась команда вырезания. В примере со сферой можно щелкнуть по основной поверхности сферы и области одной из окружностей, чтобы в поверхности образовалось только одно отверстие.
n(миг Ulil
пошхности wi
МШШКШМ
8
Полигональное моделирование (от греч. polygon - «много углов») - это простой и в то же время функциональный способ построения поверхности. Полигон представляет собой поверхность, составленную из меньших по размеру, плоских поверхностей с тремя или более сторонами. Они называются гранями (faces); линии, образующие грани, являются ребрами (edge), а концы ребер - вершинами (vertex). Работа с полигонами - это скорее грубое твердотельное конструирование, в то время как поверхности NURBS используются для органического моделирования, то есть создания пластичных, рельефных форм. Многие компании, разрабатывающие компьютерные игры, предпочитают использовать метод полигонального моделирования. Поскольку в игре предполагается быстрое взаимодействие с игроком и визуализация в реальном времени, ее геометрия не должна быть слишком сложной. Если персонаж низкополигональный, то есть построен из небольшого числа граней, он будет быстро визуализироваться и взаимодействовать с другими персонажами, что и позволяет игре работать в реальном времени (рис. 8.1).
Рис. 8.1. Полигональная модель имеет наименьшее возможное число граней. Недостаток деталей восполняется подробными текстурами. Смоделировано и текстурировано Тоби Марвином (Toby Marvin)
Полигоны и поверхности разделения 193 Однако полигоны можно использовать и для создания гладких, очень детализированных, даже органических поверхностей (рис. 8.2). Некоторые поверхности проще построить с помощью полигонов, чем поверхностей NURBS. Например, тело персонажа можно создать из цельной полигональной поверхности, но этого нельзя достичь, используя поверхность NURBS, которая может иметь всего четыре стороны. Рис. 8.2. Полигоны можно использовать для создания гладких форм, например модели банана и резких ребер, как на этом ботинке. Ботинок смоделирован Адрианом Ниу (Adrian Niu)
13.181
Поверхности разделения появились в Maya недавно. Они сочетают в себе лучшие стороны NURBS и полигонов, но есть в них и несколько особенностей, присущих только им. Поверхности разделения могут ускорить процесс моделирования, поскольку позволяют просматривать поверхность как в высоком разрешении с множеством точек, так и в низком всего лишь с несколькими точками. Если вы владеете навыками полигонального моделирования, вам будет несложно освоить работу с поверхностями разделения, потому что и в том, и в другом случае используются практически одни и те же инструменты,
194 Полигоны и поверхности разделения
Полигональное моделирование Обычно даже самая сложная полигональная модель создается на основе полигонального примитива, например куба. Преобразуя этот простой объект и работая с его компонентами, вы получаете основную форму модели. А затем вы можете продолжать построение объекта, добавляя на поверхность дополнительные, более сложные элементы. Все полигоны состоят из четырех компонентов, которые важны как для моделирования, так и для текстурирования. Это грани, ребра, вершины и проекционные координаты:
Рис. 8.3. Подсвеченная грань сферы была выделена щелчком по ее центральной точке
• грань (face) - одна из многих поверхностей, которые формируют полигональный объект как целое. Любую грань можно выбрать, выделив точку в ее центре (рис. 8.3); • ребро (edge) представляет собой границу полигональной грани {рис. 8.4); • вершина (vertex) - точка соединения ребер. Выделенные вершины окрашены в желтый цвет (рис. 8.5). При перемещении вершины изменяется форма четырех граней, в которые она входит;
Рис. 8.4. Выделенное ребро принадлежит обеим граням, находящимся по каждую сторону от него. Любое изменение положения или размера этого ребра отразится на всех гранях, с которыми оно соприкасается
• проекционные координаты (UV) используются для наложения текстур, при моделировании они не применяются. Выделенные проекционные координаты окрашены в зеленый цвет (см, главу 14).
Рис. 8.5. Выделенная вершина является общей точкой четырех граней
Полигональное моделирование 195 На начальном этапе моделирования наиболее часто используются полигональные инструменты Extrude Face (Выдавить грань) и Split Polygon (Разбить полигон). При дальнейшей работе с полигональной поверхностью применяются такие инструменты, как Extrude Edge (Выдавить ребро) и Subdivide (Разделить),
Рис. 8.6. Обычно на экране отображаются только компоненты одного вида. Контекстное меню, которое можно вызвать с помощью правой кнопки мыши, - удобный способ изменять тип отображаемых компонентов
Выделенную грань, вершину или ребро можно перемещать, вращать и изменять в размерах. Чтобы ускорить рабочий процесс, используйте контекстное меню.
Выделение и преобразование компонентов полигона 1. Создайте любой полигональный примитив (см. главу 3). 2. Правой кнопкой мыши щелкните по полигональной поверхности. 3. В контекстном меню выберите пункт Vertex (рис. 8.6). 4. Выделите несколько вершин. Область выделения можно обозначить, нарисовав рамку с помощью указателя (см. рис. 8.7).
Рис. 8.7. С помощью ограничивающей рамки три вершины выделены одновременно
5. Нажмите клавишу w или щелкните по кнопке инструмента Move Щ на панели инструментов, 6. Переместите вершины (рис. 8.8). Чтобы вызвать контекстное меню в режиме каркаса, нужно щелкнуть непосредственно по компоненту поверхности, например, по ребру. Б режиме тонирования можно щелкнуть в любом месте поверхности.
Рис. 8.8. Выделенные вершины перемещены инструментом Move. Изменилась форма всех граней, которым они принадлежат
Метод, описанный в этом разделе, можно использовать для выделения и преобразования любого полигонального компонента,
196 Полигоны и поверхности разделения При полигоном моделировании вы работаете с огромным количеством компонентов, В Maya есть специальные инструменты, которые позволяют выделять компоненты определенного типа, исключая возможность выбора других компонентов. К ним относится инструмент Backface Culling (Скрытие обратной стороны), который, скрывая точки на обратной стороне объекта, препятствует их выделению, а также инструменты, позволяющие увеличивать, уменьшать и преобразовывать области выделения.
Инструмент Backface Culling 1. В меню Create выберите пункты Polygon primitives ^ Torus {Полигональные примитивы => Тор).
Рис. 8.9. На верхнем рисунке в виде сбоку выделены грани тооа. Рекомендуется переключать виды, чтобы просмотреть область выделения с разньк углов. На нижнем рисунке изображен тор в окне Persp после удаления граней
2. Правой кнопкой мыши щелкните по полигональной поверхности и в контекстном меню выберите пункт Face. 3. На виде сбоку выделите с помощью рамки верхнюю половину тора и затем удалите грани (рис. 8.9}. 4. В меню Display щелкните по значку рядом с пунктом Custom Polygon Display (Настройка отображения полигонов). Откроется окно Custom Polygon Display Options (рис. 8.10).
Рис. 8.10. В окне Custom Polygon Display Options можно указать, бурут ли опции отображения применяться ко всем полигональным объектам или только к выделенному, выбрав пункт АН или Selected в переключателе Objects Affected
Полигональное моделирование 197 5. В выпадающем списке Backface Culling (Скрытие обратной стороны) выберите пункт On (Включено). Нажмите кнопку Apply. Части тора, находящиеся на обратной стороне вида камеры, исчезнут. Их нельзя будет выделить (рис. 8.11). Рис. 8.11. В режиме Backlace Culling компоненты на обратной стороне объекта исчезают, и вы не мажете их выделить. Эта команда применяется для всех полигональных компонентов
6. В выпадающем списке Backface Culling выберите пункт Keep Wire (Оставить каркас). Нажмите кнопку Apply. На экране отображается скелет обратной стороны, но выделять компоненты этой части поверхности нельзя (рис. 8.12). 7. В выпадающем списке Backface Culling выберите пункт Keep Hard Edges (Оставить резкие ребра). Нажмите кнопку Apply. На экране отображаются только резкие ребра обратной стороны, то есть ребра, которые находятся вдоль отверстий поверхности (рис. 8.13).
Рис. 8.12. Режим Backface Culling определен как Keep Wire. Эта установка позволяет видеть каркас объекта, но препятствует выделению компонентов, находящихся на обратной стороне
Рис. 8.13. При установке значения Keep Hard Edges на экране отображается основная форма объекта, но только с ребрами, которые ограничивают отверстие в объекте
8. В выпадающем списке Backface Culling выберите пункт Off. Нажмите кнопку Apply, чтобы вернуть параметрам Custom Polygon Display Options значения, устанавливаемые по умолчанию. Теперь можно вновь выделять обратные стороны полигональных поверхностей.
198 Полигоны и поверхности разделения Увеличение, уменьшение и преобразование области выделения L. В меню Create выберите пункты Polygon primitives ^ Sphere. 2. Правой кнопкой мыши щелкните по полигональной поверхности и в контекстном меню выберите пункт Vertex (Вершина). 3. Выделите несколько вершин (рис. 8.14). 4. В меню Edit Polygons выберите пункты Selection "=> Grow Selection Region (Выделение ^> Увеличить область выделения). Вершины, окружающие область выделения, также становятся выделенными. Повторите этот шаг, чтобы увеличить размер выделенной области (рис. 8.15).
Рис. 8.14. Выделено несколько вершин полигональной сферы. Если режим Backface Culling отключен, то точки, находящиеся на обратной стороне сферы, также выделяются Выделенные вершины
5. В меню Edit Polygons выберите пункты Selection => Shrink Selection Region (Выделение => Уменьшить область выделения). Размер выделенной области уменьшается. Повторите этот шаг, чтобы уменьшить область, 6. В меню Edit Polygons выберите команды Selection Ф Convert Selection to Faces (Выделение => Преобразовать область выделения в грани}. Выделение вершин отменено, а грани, которым они принадлежат, становятся выделенными (рис. 8.16), Область выделения компонентов любого вида можно преобразовать в область выделения ребер, вершин или проекционных координат. Некоторые инструменты моделирования полигонов применяются только к граням, например Extrude Face. Если вы уже выделили вершины, то команда Convert Selection сэкономит время, которое ушло бы на поочередное выделение граней.
Рис. 8.15. Выделять вершины по одной сложно. Команда Edit Polyijons ч* Selection => Grow Selection Region позволяет выделить точки вокруг области выделения, и количество выделенных вершин увеличивается
Полигональное моделирование
199
Команда Extrude Face (Выдавить грань) позволяет вытолкнуть грань поверхности. Сначала нужно выделить грань или грани, затем применить указанную команду и работать уже с полученными гранями,
Выдавливание граней куба 1. В меню Create выберите пункты Poly gon Primitives Cube. Рис. 8.1 Б. Выделены грани, которые были окружены выделенными вершинами, а выделение точек отменено
2. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Face. 3. С помощью рамки выделите все грани (рис. 8.17).
Рис. 8,17. Если вы выделяете рамкой весь объект целиком, выделяются и грани, находящиеся на обратной стороне объекта
4. В меню Edit Polygons выберите пункт Extrude Face. Появится манипулятор, который используется для перемещения, поворота новых граней и их масштабирования (рис. 8.18). Манипулятор отображается только на одной грани, по влияет на все выдавленные грани. Он преобразует грани локально, то есть перемещает их относительно нормали поверхности (прямая, перпендикулярная центру каждой выдавленной грани). 5. С помощью манипулятора перемещения передвиньте одну грань в направлении от центра куба, как бы выдвигая ящик письменного стола. Все вновь выдавленные поверхности также перемещаются от центра (рис. 8.19). Эта процедура упрощает создание симметричных объектов.
Рис. 8.18. Этот манипулятор появляется при выборе команды Edit Polygons c> Extrude Face
200
8
Полигоны и поверхности разделения Когда вы применяете команду выдавливания в первый раз, в центре каждого ребра грани, которую вы выбрали, появляются точки (рис. 8.18), Эти точки - центры новых граней, появившихся в результате выдавливания. Однако они остаются вырожденными до тех лор, пока вы не переместите выделенную грань или не измените ее размеры. Если этого не сделать, данные элементы создадут проблемы при конечной визуализации. Ведь на самом деле существует две поверхности, которые располагаются непосредственно друг под другом. Чтобы этого избежать, не забудьте после каждого выдавливания переместить или масштабировать грань.
Рис. 8.19. Если одна из граней выдвигается вперед, все остальные повторяют ее движение. Манипулятор масштабирования инструмента Extrude Face изменяет размеры всех выделенных граней относитепьно центров одновременно
Довольно часто требуется пропорционально масштабировать выдавленную грань. Щелкните по любому манипулятору Scale, и в центре грани появится манипулятор для пропорционального изменения ее размеров. Чтобы повернуть грань вокруг какойлибо оси, щелкните по внешнему манипулятору вращения. Появятся три манипулятора вращения (по одному для каждой оси).
Выдавливание ребер 1. В меню Create выберите пункты Polygon Primitives Cube.
Рис. 8.20. Удалена одна грань куба, на месте которой образовалось отверстие
2. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Face. 3. Выделите грань на боковой стороне куба и нажмите клавишу Delete. Грань исчезнет, и вы увидите куб изнутри (рис. 8.20). Можно удалить ребро или вершину, но это не откроет куб; останется большая грань, определяемая тремя ребрами. Чтобы убедиться в этом, выделите несколько вершин и в меню Edit Polygons выберите пункт Delete Vertex,
Рис. 8.21. Выделены ребра на правой и левой сторонах отверстия
Полигональное моделирование
201
4. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Edge, 5. Выделите левое ребро созданного отверстия и, удерживая нажатой клавишу Shift, выделите правое фис. 8.21). 6. В меню Edit Polygons (Редактировать полигоны) выберите пункт Extrude Edge (Выдавить ребро). 7. Переместите ребро на некоторое расстояние от куба и немного в сторону. Создано две новых грани, а куб теперь выглядит как открытая коробка (см. рис. 8.22).
Рис. 8.22. При выдавливании ребер создаются новые грани. При перемещении одного ребра другое перемещается в том же направлении по одной оси и в противоположном - по другой. На рисунке показаны два возможных результата
Рис. 8.23. У объекта слева в результате выдавливания появилось ребро, которое принадлежит трем граням, а у объекта справа такого ребра нет, поскольку у него есть отверстие. Модель, ребро которой принадлежит более чем двум граням, не самая удачная. Такой объект нельзя преобразовать в поверхности разделения
Ребро может принадлежать только одной грани или двум. Это значит, что выдавливать следует только ребра полигона, смежные с отверстием. Нарушать это правиле не рекомендуется (рис. 8.23).
202 Полигоны и поверхности разделения С помощью инструментов Extrude Face и Extrude Edge выделенные ребро или грань можно выдавить вдоль предопределенной кривой. Указывая число делений в опциях Extrude Face или Extrude Edge, вы управляете числом дополнительных полигонов, которые добавляются при выдавливании. Чем больше значение Division (Деление), тем больше деталей будет добавлено и тем более гладкой будет конечная поверхность.
Выдавливание ребер и граней вдоль кривой пути 1. В меню Create выберите пункты Polygon Primitives t> Cube. 2. Выполните команды меню Create CV Curve Tool.
Рис. 8.24. В качестве пути выдавливания используется кривая, созданная на основе контрольных точек
3. Создайте кривую, начало которой находится на грани или ребре, которые требуется выдавить, а конен - в том месте, где должно завершиться выдавливание. Таким образом вы определите кривую пути (рис. 8.24), 4. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Face или Edge, 5. Выделите грань или ребро, которые нужно выдавить вдоль кривой пути (рис. 8.25). 6. Удерживая нажатой клавишу Shift, выделите кривую пути. 7. В меню Edit Polygons щелкните по значку рядом с пунктом Extrude Face, если выделена грань, или рядом с пунктом Extrude Edge, если выделено ребро. Откроется окно Extrude Face Options или Extrude Edge Options.
Рис. 8.25. Грань выделена и готова к выдавливанию
»
-"
ЬВМУаЮ"
jrj otheiVok».
inefSES— " •
J
[J? ' S-iMMFaes
44*1
Since
CaoM5
1«,
*B*
{
Cbn
|
Рис. 8.26. Активируйте флажок Use Selected Curve for Extrusion. Это гарантирует, что выдавленные поверхности 6уд]ут следовать пути, который определяется выделенной кривой
Полигональное моделирование 203 8. Убедитесь, что в разделе Other Values (Другие значения) активирован флажок Use Selected Curve for Extrusion (Использовать выделенную кривую для выдавливания) - рис. 8.26.
Рис. 8.27. Параметр Divisions определен по умолчанию равным 1, поэтому в результате поверхность выдавливается по прямой
9. Нажмите кнопку Apply. Компонент выделенной поверхности выдавлен. В настройках по умолчанию установлено только одно деление, поэтому новая поверхность выдавливается по прямой, соединяющей начальную и конечную точки кривой пути (рис. 8.27). 10. Не закрывая окно Extrude Options, средней кнопкой мыши щелкните в рабочем окне, а затем отмените одно действие так, чтобы компонент и кривая были все еще выделены. 11. Б окне Extrude Options в разделе Other Values присвойте параметру Divisions (Деления) значение 10 (рис. 8.28).
Рис. 8.28. Увеличение параметра Divisions до 10 разделяет конечную выдавленную поверхность на достаточное количество сегментов, что позволяет поверхности точно следовать вдоль кривой пути
Рис. 8.29. Выделенная грань выдавлена вдоль кривой пути
12. Нажмите кнопку Extrude Face или Extrude Edge. Выделенные грань или ребро теперь выдавлены вдоль кривой пути (рис. 8.29).
П
При изменении параметра Twist (Скрутка) выдавленные полигоны поворачиваются по мере их следования вдоль кривой.
204 Полигоны и поверхности разделения При изменение параметра Taper/Taper Curve (Сузить/сузить кривую) выдавленные полигоны масштабируются по мере их следования вдоль кривой (рис. 8.30). Инструмент Extrude Vertex (Выдавить вершину) позволяет создавать вокруг выделенной вершины дополнительные полигоны, образующие форму пирамиды, при этом вершина удаляется от поверхности на расстояние, определенное пользователем.
Выдавливание граней из вершины 1. В меню Create выберите пункты Polygon Primitives => Cube.
Рис. 8.30. Выдавленные поверхности уменьшаются по мере удаления от начальной грани
2. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Vertex. 3. Выделите вершину, которую требуется выдавить (рис. 8.31). 4. В меню Edit Polygons щелкните по значку рядом с пунктом Extrude Vertex. Откроется окно Extrude Vertex Options. 5. Присвойте параметру Extrude Length (Расстояние выдавливания) значение 2 (рис. 8.32). Таким образом вы определите, как далеко от поверхности переместится выделенная вершина.
Рис. 8.31. При подготовке к выдавливанию выделена угловая вершина
6. Нажмите на кнопку Extrude Vertex. Вершина выдавлена, при этом созданы дополнительные грани, образующие пирамидальную форму (рис. 8.33). Параметр Extrude Width определяет относительный размер поддерживающих вершин, которые использовались для создания выдавленной поверхности. При его изменении пирамида становится шире.
Рис. 8.32. Параметр Extrude Length определяет, как далеко от поверхности переместится выделенная вершина
Полигональное моделирование
205
Параметр Divisions определяет, сколько раз будет разделена выдавленная поверхность. При его увеличении поверхность делится на дополнительные полигоны (рис. 8.34).
Рис. 8.33. При выдавливании вершины создается пирамидальная форма
Рис. 8.34. Параметру Divisions присвоено значение 2. Это создает дополнительную геометрию поверхности на выдавленном объекте
Инструмент Split Polygon (Разбить полигон), усовершенствованный в последних версиях Maya, широко используется при полигональном моделировании. Он позволяет разбить одну грань на две или более граней при помощи ребра, определенного пользователем. Чтобы сэкономить время, можно разбивать несколько граней одновременно. В окне проекции Persp объект определенным образом искажается, поэтому определить середину ребра сложно. Чтобы разбить ребро в нужном месте, инструмент Split Polygon следует привязать к центральной точке ребра или точке, определенной пользователем. Как правило, при моделировании рекомендуегсн ограничиться трех- и четырехсторонними гранями, то есть треугольниками (triangles) и квадратами (quads), поскольку для них проще предсказать результат применения других инструментов редактирования. Если же у грани пять или более сторон, нужно разбить ее на несколько граней с меньшим числом сторон,
206 Полигоны и поверхности разделения Разбиение грани 1. В меню Create выберите пункты Polygon Primitives О Cube. 2. В меню Edit Polygons щелкните по значку рядом с пунктом Split Polygon Tool. Откроется окно Tool Settings {Параметры инструмента), в котором находятся опции инструмента Split Polygon (Разбить полигон).
Рис. 8.35. Инструмент Split Polygon позволяет разбить полигон пополам, на три части, на четыре части и т.д.
3. Отметьте галочками флажки Snap to Magnets (Привязка к магнитам) и Snap to Edge (Привязка к ребру). Поставьте ползунок Magnet Tolerance (Допуск магнита) примерно на середину диапазона (рис. 8.35). 4. Перетащите указатель мыши к середине верхнего ребра. Точка должна привязаться к центру ребра (рис. 8.36). Отпустите кнопку мыши. 5. Перетащите указатель мыши в середину ребра, которое находится на противоположной стороне верхней грани куба (рис. 8.37). Если включен режим Snap to Edge, точки можно выделять только на ребре.
Рис. 8.36. С помощью инструмента Split Polygon можно поместить точку точно в центр ребра
6. Нажмите клавишу Enter. Грань разбита пополам. 7. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Edge.
Рис. 8.37. Новое ребро определяется двумя точками, размещенными с помощью инструмента Split Polygon. Нажатие клавиши Enter завершает выполнение команды. Однако вы можете продолжить разбиение (и пройтись по всему кубу), щелчком мыши добавляя на каждое ребро по одной точке
Полигональное моделирование 207 8. Выделите вновь созданное ребро и переместите его вверх. Объект должен быть похож на игрушечный домик (рис. 8.38). 9. В меню Edit Polygons выберите пункт Split Polygon Tool.
Рис. 8.38. Новое ребро перемещено вверх, и наш куб превратился в игрушечный домик. Заметьте, что фасад дома образует пять ребер. Грань, в которой больше четырех ребер, не слишком удачна
10. Перетаскивайте указатель мыши вдоль левой стороны куба, пока точка не привяжется к верхнему ушу. Повторите то же самое для правой стороны (рис. 8.39), И. Нажмите клавишу Enter. Теперь грань с пятью сторонами, которая образовывала фасад дома, разбита на две грани - треугольник и квадрат. Убедитесь, что при разбиении всегда создается ребро. Если вы щелкните по одному ребру и нажмете клавишу Enter, не щелкнув по другому ребру той же грани, вы создадите лишнюю вершину. Это еще один пример неудачной конструкции. Чтобы избежать этого, не забудьте отменить действие, если инструментом Split Polygon не было создано новое ребро.
Рис. 8.39. Создано новое ребро: которое разбивает переднюю грань на две отдельные грани
Иногда привязка к центру может затруднить создание других разбиений. Чтобы отключить привязку, в диалоговом окне Tool Settings в разделе Split Polygon Settings снимите флажок Snap to Edge. He обязательно осуществлять привязку в середине ребра, привязывать можно и к нескольким точкам. Если требуется разбить полигон на три части, осуществите привязку в точке, находящейся от вершины на расстоянии одной трети длины ребра. В диалоговом окне Tool Settings перейдите в раздел Split Polygon Settings, и в поле Number of Magnets (Число магнитов) введите значение 2. Создано две равномерно распределенные вдоль ребра точки, к которым будет применяться привязка (нужно также ак тивировать флажок Snap to Magnets}.
208 Полигоны и поверхности разделения Разбиение множества полигонов инструментом Split Polygons - утомительный процесс. А с помощью инструмента Cut Face (Разрезать грань} грани можно разрезать так же, как ножом кусок сыра (см. рис. 8.40). Он добавляет на полигон (или на весь полигональный объект) ребра с помощью спроецированной линии, положение которой вы определяете по своему желанию (рис. 8.41). Линия проецируется под углом зрения камеры, разрезая все выделенные и пересекающиеся с ней полигоны. Если в настройках Cut Face выделена опция удаления, одна из частей разрезанного объекта будет удалена. Это позволяет создать и зеркально отобразить экземпляр объекта, придав ему тем самым законченную форму (так вы бы поступили с головой персонажа).
Рис. 8.40. Инструмент Cut Face позволяет интерактивно разрезать любые поверхности, при этом одна часть поверхности либо удаляется, как показано на рисунке, либо поверхность просто разрезается и обе части остаются на сцене Разрезающая линия
Короткая линия показывает, какая часть объекта будет удалена
Рис. 8.41. При помощи Cut Face можно разрезать поверхность в любом месте. Короткая кривая определяет, какая из двух частей, разграниченных линией, будет удалена
Полигональное моделирование Разрезание поверхности инструментом Cut Face 1. Создайте полигональный примитив куб и выделите его.
Рис. 8.42. Настройки диалогового окна Polygon Cut Face Tool Options позволяют разрезать поверхности в точно заданном месте или интерактивно определять положение разрезающей линии. Вы можете изменить направление или плоскость разреза
2. И меню Edit Polygons щелкните по значку рядом с пунктом Cut Faces. Откроется окно Polygon Cut Face Tool Options (рис. 8.42). 3. Щелкните по кнопке Enter Cut Tool (Ввести инструмент разрезания). Появится линия, представляющая разрезающую плоскость (рис. 8.43). 4. Щелкните в рабочем окне и перетащите линию, чтобы определить положение разрезающей плоскости на поверхности. 5. Чтобы разрезать поверхность, отпустите кнопку мыши (рис. 8.44). Л и н и я спроецирована па объект, а в тех местах, где она пересекает поверхность, сделаны разрезы. Заметьте, что не было удалено ни одной поверхности они были добавлены.
Рис. 8.43. Вы можете перемещать и поворачивать разрезающую линию до тех пор. пока вы не достигнете нужного результата
Рис. 8.44. Чтобы разрез проходил через поверхность, разрезающая линия проецируется под выбранным углом зрения камеры 14э-я]
210
Полигоны и поверхности разделения
6. В диалоговом окне Polygon Cut Face Tool Options установите флажок Delete the Cut Faces (Удалить отрезанные грани) - рис. 8.45. 7. Нажмите кнопку Enter Cut Tool and Close. Указатель мыши примет форму стрелки.
Deleti!
Delete the cut fa
Рис. 8.45. Если флажок Delete the cut faces отмечен галочкой, то отсекаемая поверхность удаляется
8. Чтобы выбрать еще одну разрезающую плоскость, щелкните по линии и перетащите ее вдоль поверхности. 9. Чтобы разрезать поверхность, отпустите кнопку мыши. Отсекаемая поверхность будет удалена (рис. 8.46). Короткая линия, перпендикулярная разрезающей, указывает на отсекаемую поверхность, которая будет удалена (рис. 8.41), Удерживайте нажатой клавишу Shift, чтобы выровнять разрезающую линию по горизонтали, вертикали или под углом 45°. а разрез сделать более точным. Инструмент Poke Faces (Вытолкнуть грани) используется для разделения выделенной грани, при этом в модель добавляются дополнительные детали и точки выделения. Действие инструмента Poke Faces напоминает работу Subdivide -он разрезает выделенную грань на идеальные треугольники. Однако у инструмента Poke Faces несколько иная специализация и определяемые ей преимущества: когда поверхности разделены, вам остается только переместить новые полигоны с помощью манипулятора.
Рис. 8-46. Отсекаемая поверхность удаляется, остается лишь часть начальной поверхности
Полигональное моделирование
211
Выталкивание грани полигона с помощью инструмента Poke Faces Выделенная грань
1. Создайте полигональный примитив куб. 2. Правой кнопкой мыши щелкните по поверхности куба и в контекстном меню выберите пункт Face. 3. Выделите одну или более граней, которые нужно вытолкнуть (рис. 8.47).
Рис. 8.47. Выделенная грань будет разбита с помощью команды Poke
4. В меню Edit Polygons выберите пункт Poke Faces. Каждая выделенная грань разбивается па четыре треугольника (рис. 8.48). 5. Щелкните по манипулятору и переместите его на некоторое расстояние от поверхности. По мере удаления манипулятора грань приобретает пирамидальную форму (рис. 8.49).
Рис. 8.48. Выделенная грань разбита на четыре треугольника
Рис. 8.49. Инструмент Poke создает манипулятор в центральной точке вытолкнутой грани, с помощью которого можно сделать новую геометрию как выпуклой, так и вогнутой
Инструмент Wedge Face (Расклинить грань) является разновидностью инструмента Extrude Face. Он создает угловые клинья, выдавливая полигональные грани по дуге (рис. 8.50). Этот инструмент значительно экономит время при создании полигональных поверхностей, которые должны быть получены перемещением и поворотом.
Рис. 8.50. Примитив куба с клиньями
212 Полигоны и поверхности разделения Чтобы создать клин, не прибегая к помощи инструмента Wedge Face, вам пришлось бы выдавливать грани одну за другой, а затем поворачивать каждую из них по дуге. Ту же самую задачу можно выполнить гораздо проще, воспользовавшись инструментом Wedge Face.
Расклинивание грани полигона 1. Создайте полигональный примитив куб. 2. Правой кнопкой мыши щелкните по объекту и в контекстном меню выберите пункт Edge, 3. Выделите ребро, вдоль которого будут изгибаться или образовывать дугу выдавленные поверхности (рис. 8.5 П.
Рис. 8.51. Выделенное ребро определяет положение оси, по которой будет повернут клин, а также направление выдавливания
4. Правой кнопкой мыши щелкните по поверхности и в контекстном меню выберите пункт Face. 3. Чтобы выделить грань одновременно с ребром, щелкните по ней, удерживая нажатой клавишу Shift (рис. 8.52). 6. В меню Edit Polygons выберите п у н к т Wedge Faces. Откроется диалоговое окно Polygon Wedge Faces Options (рис. S.53). 7. Нажмите кнопку Apply. Вокруг выделенного ребра дугой создана ногая геометрия под углом в 90° от началыюй выделенной грани (рис. 8.54),
Рис. 8.52. Выделена правая грань куба
8. Правой кнопкой мыши щелкните по поверхности и в контекстном меню выберите пункт Edge. 9. Выделите на противоположной стороне куба ребро, вдоль которого будут изгибаться или образовывать дугу новые выдавленные поверхности {рис. 8.55).
Рис. 8.53. В диалоговом окне Polygon Wedge Faces Options установите угол клина и количество клиньев в новой поверхности
Полигональное моделирование
213
10. Правой кнопкой мыши щелкните по поверхности и в контекстном меню выберите пункт Face, 11. Чтобы выделить грань одновременно с ребром, щелкните по ней, удерживая нажатой клавишу Shift (рис. 8.56),
Рис. 8.54, Вокруг выделенного ребра дугой создана новая геометрия. Чтобы сделать клин более гладким, добавлены дополнительные полигоны
Рис. 8.55. Ребра поверхности приобретают важность при повороте и выдавливании, осуществляемым командой Wedge. Выделите ребро, вокруг которого нужно выдавить клинья
Рис. 8.56. Выделите грань, вокруг которой нужно образовать дугу
12. Присвойте параметру Wedge Angle (Угол клина) значение 120, a Wedge Divisions (Число клиньев) значение 8, затем нажмите кнопку Apply. Вокруг выделенного ребра дугой создана новая геометрия под углом в 120° от начальной выделенной грани. Она состоит нз восьми клиньев, расположенных по дуге (рис. 8.57). Новый инструмент Chamfer Vertex (Ско сить вершину) удаляет выделенную вершину, создавая скошенный угол. В результате получается полигон с тремя сторонами, в котором удалена начальная вершина.
Рис. 8.57. Изменяя атрибут Wedge Angle, можно управлять размером дуги
214
Полигоны и поверхности разделения
Скос угла полигона 1. В меню Create выберите пункты Polygon Primitives ^> Cube. 2. Правой кнопкой мыши щелкните по поверхности и в контекстном меню выберите пункт Vertex, 3. Выделите вершину угла, который требуется сделать скошенным (рис. 8.58). 4. В меню Edit Polygons выберите пункт Chamfer Vertex (рис. 8.59). Угол полигона становится скошенным, а его вершина заменяется гранью с тремя сторонами (рис. 8.60). Если в окне инструмента Chamfer Vertex активен флажок Delete Faces (Удалить грани), то на месте скошенного угла остается треугольное отверстие. Настраивая в окне инструмента Chamfer Vertex параметр Width (Ширина), вы изменяете длину ребра, которую образует скошенный угол, а вновь созданный треугольник становится шире или уже. Новый инструмент Smooth Proxy (Сгладить с управлением) идеально подходит для ситуаций, в которых лучше работать с моделями с низким разрешением, но при этом необходимо видеть, как модель будет выглядеть после сглаживания. Он позволяет просмотреть сглаженную версию модели с низким разрешением (как если бы вы применили к ней команду Smooth). Исходная поверхность с низким разрешением также отображается на экране. Поэтому вы можете работать с меньшим числом точек и одновременно видеть конечную форму.
Рис. 8.58. Выделите вершину, которую нужно сделать скошенной
Texture
i! . I • .
Рис. 8.59. В меню Edit Polygons выберите пункт Chamfer Vertex
Рис. 8.60. Результат применения команды Chamfer Vertex
Полигональное моделирование 215 Низкое разрешение
Когда вы применяете команду Smooth Proxy к полигональной модели, програм ма создает новый слой, на котором находится сглаженная поверхность с высоким разрешением. Это позволяет вам просматривать обе версии одновременно, а при необходимости скрывать один из слоев.
Инструмент Smooth Proxy 1. В режиме выделения объектов выберите полигональный объект,
Высокое разрешение
Рис. 8.61. Инструмент Smooth Proxy позволяет просмотреть сглаженную версию модели во время работы с версией с низким разрешением. На этом рисунке объект с низким разрешением имеет форму куба, однако при сглаживании он больше похож на сферу Низкое разрешение
2. В меню Polygons выберите пункт Smooth Proxy. Maya создаст новую, сглаженную версию модели, сохранив при этом оригинал. Каждая новая форма добавляется на отдельный слой; чтобы упростить моделирование, можно сделать один из слоев невидимым (рис. 8.61). 3. Правой кнопкой мыши щелкните по исходному объекту и в контекстном меню выберите пункт Vertex. 4. Выделите и переместите одну из вершин. В версии модели с высоким разрешением отразятся изменения, внесенные в модель с низким разрешением (рис. 8.62). В настройках инструмента Smooth Proxy можно определить сглаживание версии модели с высоким разрешением, изменяя число разделений.
Высокое разрешение
Рис. 8.62. Переместив всего одну точку на поверхности с низким разрешением, вы изменяете множество точек на поверхности с высоким разрешением
Инструмент Subdivide (Разделить) разбивает грань на четырехугольники (грани с четырьмя сторонами) или на треугольники (грани с тремя сторонами). Это быстрый способ добавления на поверхность дополнительных граней. Однако не стоит путать этот процесс со сглаживанием поверхностей. В следующем примере мы воспользуемся инструментами Subdivide и Extrude Face, чтобы создать дверь,
216 Полигоны и поверхности разделения Разделение полигональной грани 1. В меню Create выберите пункты Polygon Primitives ^ Cube. Построение обычно начинается с куба, в который приблизительно вписывается объект, а затем из куба моделируется конечный объект с помощью команд меню Edit Polygons.
Рис. 8.63. Кубу придали форму двери, изменив его размеры
2. Придайте кубу форму двери (рис. Я.63). 3. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Face, 4. Выделите грань на передней части куба. 5. В меню Edit Polygons выберите команду Subdivide. Грань разбита на четыре части {рис. 8.64). Новые грани остаются выделенными. 6. В меню Edit Polygons выберите команду Extrude Face. Появятся новые грани и манипулятор. 7. Используя манипулятор, слегка уменьшите размер граней (рис. Я.65). 8. В меню Edit Polygons снова выберите команду Extrude Face. Появятся новые грани и манипулятор.
Рис. 8.64. Грань оазделена на чегыре грани меньшего размера. Чтобы разделить грань на большее количество граней, щегкните по значку рядом с пунктом Edit Polygons * Subdivide и в диалоговом экне измените параметр Subdivisions Levels Рис. 8.65 Размеры выдавленных граней уменьшаются по огношению к их центрам
9. Уменьшите размер новых граней и переместите их к середине объекта. В результате должна получиться дверь с четырьмя панелями (рис. 8.66), У только что созданных полигональных объектов, как правило, острые ребра и углы. Их можно округлить с помощью команд Polygons => Smooth {Полигоны с> Сгладить), которая разделяет поверхности на множество полигонов меньшего размера, таким образом округляя их углы и ребра.
Рис. 8.66. Дверь с четырьмя панелями. Если бы до запуска функции Subdivide была одновременно выделена грань F-a противоположной стороне двери, то, проделав те же самые шаги, вы смоделировали бы одновременно и обратную сторону двери
Полигональное моделирование 217 Bf Polygon Rmnolh Options
Сглаживание полигона 1. Выделите полигональный объект, например, дверь из предыдущей задачи.
Рис. 8.67. Диалоговое окно Polygon Smooth Options
2. В меню Polygons выберите пункт Smooth. Откроется диалоговое окно Polygon Smooth Options (рис. 8.67) Если в нем определен, высокий уровень разделения (два и более), то создаются более гладкие объекты с большим числом граней. Парамеир Continuity опре деляет, насколько новый объект будет походить на оригинал. Если параметру Continuity присвоено небольшое значение, то объект более близок к ориги палу. При большом значении создают ся очень округлые формы. 3. Ползунок Subdivision Levels (Уровни разделения) переместите на значение 3. 4. Нажмите кнопку Smooth. Объект стано вится гладким (рис. 8.68).
Рис. 8.68. Начальная форма двери и сглаженная модель
Перед тем как применять команду Smooth нужно завершить формирование основной структуры полигонального объекта. При сглаживании создается объект с уплотненной сеткой и большим количеством граней, с которым трудно работать. В диалоговом окне Polygon Smooth Options можно присвоить параметру Subdivisions Levels значение 4; однако обычно достаточно и значения 3 (при большем значении из-за избытка информации о точках поверхность становится громоздкой, усложняется ее визуализация и отображение в рабочих окнах).
218
Полигоны и поверхности разделения Изменить уровень сглаживания можно и после завершения операции, щелкнув по заголовку polySmoolhFacel, который должен находиться в верхней части списка узлов Inputs в окне Channel Box. Ниже появится новый раздел, в котором вы увидите поле Divisions. Диапазон его изменения составляет от 0 (без сглаживания) до 4 (очень гладкая поверхность) - рис. 8.69. Можно сгладить только часть полигональной поверхности. В режиме компонентов выберите грани поверхности, которые требуется сгладить, а затем примените команду Smooth (рис. 8.70).
«иен 1
ll Illll-i.
pCubeZ Translate X'P TS! Translate YJp.]5 ?««slateZ -iUn.-
toate л РеМб V J
SHAPES pCubeShapei! INPUTS palySmoathFacel Continuity I : Keep Border Keep Selection Keep Tgfggttatio
С помощью команды Polygons => Reduce (Полигоны Уменьшить} количество граней в выбранной сетке или в поднаборе сеток уменьшается в процентном отношении, определенном пользователем. В пятой версии Maya инструменты сокращения количества полигонов значительно улучшены. При создании компьютерных игр и других интерактивных сред очень важно следить за тем, чтобы число полигонов было как можно меЕ1ьшим. Это позволяет свести к минимуму время визуализации. Решить задачу помогает инструмент Reduce.
Рис. 8.69. В поле узлов Inputs в Channel Box можно изменить опции команды Smooth после того, как она была запущена. Однако если в поверхность были внесены дополнительные изменения, возвратившись к опциям в разделе узла polySmciothFace и переопределив их, вы можете получить неожиданные результаты
Рис. 8.70. Слева выделены грани на верхней и нижней частяк объекта. Справа представлен результат сглаживания. Функция Smooth выполняется топько при выделении необходимых полигональных объектов или граней объекта; производить сглаживание, выделяя вершины или ребра, нельзя
Полигональное моделирование [219 Уменьшение числа граней в полигональной сетке 1. Выделите полигональный объект или набор граней, из которого требуется убрать полигоны (рис. 8.71), 2. Б меню Polygons выберите пункт Reduce. Откроется диалоговое окно Polygon Reduce Options. 3. Введите в поле Reduce by (%) (Уменьшить на (%)) число полигонов в процентном отношении, на которое вы хотите сократить сетку, например, 80% (рис. 8.72). Рис. 8.71. Полигональный объект с очень большим количеством полигонов
4. Нажмите кнопку Reduce. Плотность полигональной сетки уменьшилась на 80% от начального числа полигонов (рис. 8.73).
У Polygon Reduce Options Ed!'
«3lp
Рис. 8.72. Определите в поле Reduce by (%) нужное процентное соотношение сокращения, в данном случае-80%
Рис. 8.73. Количество полигонов сократилось на 80%
Если вы хотите оставить копию оригинала, то есть поверхность с высоким разрешением, в диалоговом окне Polygon Reduce Options включите опцию Keep Original.
220
Полигоны и поверхности разделения
Моделирование поверхностей разделения Формирование поверхности разделения, сочетающее в себе методы NURBS- и полигонального моделирования, имеет два режима: стандартный и полигональный. В полигональном режиме для работы с поверхностями можно использовать все полигональные инструменты. 13 стандартном режиме вы в основном работаете с вершинами, похожими на контрольные (CV) вершины NURBS. Но и в стандартном режиме у форм есть ребра и грани, как и у полигона. Этот режим позволяет переключаться между уровнями отображения (display levels), или различными уровнями детализации объекта (рис. 8.74),
Рис. 8.74. Хаффзр (так зовут это странное создание) был разработан Роем Майлзом (Roy Miles) и смоделирован Эндрю Бриттом (Andrew Britt) с помощью поверхностей разделения. Слева - объект к полигональном режиме, справа s стандартном режиме, в котором отображаются вершины; наверху- в стандартном режиме, в котором компоненты не видны
В полигональном режиме отображаются ребра полигональной формы, которые окружают сглаженную поверхность - поверхность разделения. В этом режиме несглаженная поверхность имеет те же самые компоненты, что и любой другой полигон. Стандартный режим включает к себя различные наборы компонентов, с которыми можно работать на разных уровнях отображения. Заметьте, что поверхности разделения, как и поверхности NURBS, могут иметь низкий, средний и высокий уровни сглаживания, которые активизируются клавишами 1, 2 и 3. Однако их не стоит путать с уровнями отображения, которые реально (а не только в окне вида) усложняют геометрию поверхности (рис. 8.75).
Рис. 8.75. На рисунке представлены две копии цилиндра разделения. Тот, что слева, находится на уровне отображения 0, а тот, что справа, на уровне отображения 1
Моделирование поверхностей разделения 221
Компоненты поверхности разделения Поверхности разделения в стандартном режиме состоят из компонентов четырех видов - граней (face), вершин (vertex), проекционных координат ( U V ) и ребер (edge): • Рис. 8.76. Поверхность разделения находится на нулевом уровне отображения, на экране представлены ее грани
грань обычно смещена относительно истинной поверхности. У нее может быть три или четыре стороны, однако для последующего моделирования поверхности разделения более подходят четырехугольники. Цифры соответствуют текущему уровню отображения (рис. 8.76);
• вершина обычно смещена относительно истинной поверхности. Она обозна чается номером уровня отображения, которому принадлежит. Если вершину переместить, она поведет за собой об ласть поверхности, которая находится к ней ближе всего (рис. 8.77);
Рис. 8.77. Вершина разделения, находящаяся на первом уровне отображения, перемещена. На эти изменения поверхность реагирует во многом так же, как и поверхность NURBS на перемещение контрольной вершины
• проекционные координаты используются не в моделировании, а в текстурировании (см. главу 14). При выделении они становятся зелеными (рис. 8.78);
Рис. 8.78. Проекционным координатвм не соответствует какой-либо уровень отображения. Поэтому они отображаются точками, а не числами
222 Полигоны и поверхности разделения • ребро представляет собой границу грани (рис. 8.79).
Выделение компонента поверхности разделения 1. В меню Create выберите пункты Subdiv Primitives => Sphere (Примитивы разделения Сфера). 2. Нажмите клавишу 3, чтобы установить высокий (fine) уровень сглаживания поверхности разделения (рис. 8.80). Поверхность станет более гладкой. Однако следует учесть, что изменение этих параметров влияет только на отображение модели, а не на ее реальную геометрию.
Рис. 8.79. В стандартном режиме выделено ребро сферы
3. Правой кнопкой мыши щелкните по сфере и в контекстном меню выберите пункт Face (Грань) -рис. 8.81. На экране появятся грани сферы, то есть куба, в который вписана сфера. 4. Выделите и переместите грант, (см. рис. 8.82).
Рис. 8.80. Слева направо сфера с различными параметрами Subdiv Smoothness: Rough, Medium и Fine
Рис. 8.81. Чтобы Еызвать контекстное меню поверхностей разделения, щелкните по сфере правой кнопкой мыши. Оно открывает доступ к большинству опций, которые потребуются при работе с поверхностями разделения
Моделирование поверхностей разделения 223
Создание рельефа поверхностей разделения Maya позволяет быстро переходить с одного уровня детализации на другой. Ниже представлено разъяснение некоторых терминов, которые потребуются для освоения данной процедуры:
Рис. 8.82. Грань перемещена, а сфера удлинилась
Рис. 8.83. Поверхность разделения показана на О, 1, 2 и 3 уровнях отображения. По умолчанию у сферы есть только уровни 0 и 1. Чтобы получить доступ к более высоким уровням, поверхность нужно детализировать с помощью команды Reline
• Display level (Уровень отображения), В Maya существует несколько уровней отображения поверхностей разделения, или детализации. Это позволяет очень гибко управлять формой объекта: можно переместить одну из множества точек, расстояние между которыми па поверхности настолько мало, что подобное изменение повлияет лишь на незначительную область; можно работать с меньшим числом точек, расстояние между которыми на поверхности велико и любая модификация повлечет за собой изменение большой области объекта (рис. 8.83);
224 Полигоны и поверхности разделения • Refine {Детализирование). Эта функция присваивает выделенной области поверхности более высокий уровень детализации. Например, если поверхность находится на уровне 1, команда Refine отобразит выделенную область с помощью точек второго уровня; • Finer (Четче) и Coarser (Грубее). Данные команды позволяют быстро перемещаться на более высокий (finer) пли более низкий (coarser) уровень детализации.
Рис. 8.84. Меню Display Level позволяет выбрать любой из существующих уровней отображения
Изменение уровней детализации 1. В меню Create выберите пункты Subdiv Primitives & Cylinder. 2. Нажмите клавишу 3, чтобы установить высокий уровень сглаживания поверхности разделения. 3. Правой кнопкой мыши щелкшгге по цилиндру и в контекстном меню выберите пункт Vertex. 4. Правой кнопкой мыши щелкЕШте по цилиндру и и контекстном меню выберите пункты Display Levels 2 (рис. 8.84). Появляется множество точек, помеченных цифрой 2 (рис. 8.85).
Рис. 8.85. По умолчанию точки второго уровня отображаются ни цилиндре только там, где требуется дополнительная детализация. Чтобы эти точки были равномерно распределены, выберите первый уровень и произведите детализацию
Моделирование поверхностей разделения 5. Правой кнопкой мыши щелкните по цилиндру и в контекстном меню выберите пункт Coarser (рис. 8.86). Уровень отображения уменьшится до 1 (рис. 8.87). 6. Правой кнопкой мыши щелкните по цилиндру и в контекстном меню выберите пункт Finer. Это восстановит второй уровень отображения.
Рис. 8.86. Чтобы изменить уровень отображения, следует выбрать пункты Coarser или Finer из контекстного меню
Детализирование поверхности разделения 1. В меню Create выберите пункты Sub div Primitives ^> Cube. 2. Нажмите клавишу 3, чтобы установить высокий уровень сглаживания поверхности разделения. 3. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Vertex. 4. Выделите вершину (рис. 8.88).
Рис. 8.87. Изображенный на этом рисунке цилиндр поверхности разделения находится на уровне отображения 1
Рис. 8.88. Выделите вершину, чтобы определить область, которая будет детализирована
15Э-81
5. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Refine. В области вокруг начальной точки нули заменились на единич ки, количество которых существенно превысило число нулей (рис. 8.89).
Рис. 8.89. С помощью команды Refine детализируется только область вокруг выделенного компонента
226 Полигоны и поверхности разделения 6. Правой кнопкой мыши щелкните по кубу и в контекстном меню еще раз выберите пункт Refine. 7. Выделите точку и переместите ее (см, рис. 8.90). 8. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Display Level ^> 0. 9. Выделите точку и переместите ее (см. рис. 8.91). Изменения, внесенные в точки второго уровня, видны и во время работы с точками нулевого уровня. Это позволяет быстро переключаться между уровнями детализации.
Рис. 8.90. Точка выделена и перемещена. Высокая детализация области позволяет ювелирно оттачивать форму объекта
Команда Refine также работает для ребер и граней. Детализацию можно проводить вплоть до уровня 13. Однако не рекомендуется применять уровень выше третьего, так как это значительно увеличивает время, отведенное на визуализацию и просчет поверхности.
В
Нельзя удалить компонент поверхности разделения. Если вы преобразуете любой компонент на первом или более высоком уровне отображения и затем попытаетесь удалить его, он вернется в исходное положение.
Рис. 8.91. Вы можете воздействовать на большие области поверхности, возвратившись на нулевой уровень отображения
Моделирование поверхностей разделения
227
Полигональный режим поверхности разделения
Рис. 8.92. Сферу сделали более плоской, чтобы она напоминала панцирь черепахи
Стандартный режим предназначен для добавления мелких деталей, а для создания основной структуры поверхности применяется полигональный режим. Объект, как правило, проходит путь от простого к сложному: ЗО-художник сначала моделирует объект из полигонов и получает грубую форму, а затем преобразует ее в поверхности разделения, чтобы довести модель до совершенства. Этот подход помогает быстрее работать, поскольку конструкция полигонального примитива куба проще, чем конструкция того же куба на основе поверхностей разделения. Однако следует помнить, что до начала детализации в стандартном режиме необходимо завершить все операции, которые вы хотели произвести в полигональном режиме, поскольку при частом переключении между режимами можно потерять внесенные ранее изменения.
Моделирование черепахи из поверхностей разделения в полигональном режиме 1. В меню Create выберите Subdiv Primitives "=> Sphere. 2. Нажмите клавишу 3, чтобы установить высокий уровень сглаживания поверхности разделения. 3. Уменьшите сферу по оси Y, сделав ее более плоской (рис. 8.92), 4. Правой кнопкой мыши щелкните по сфере и в контекстном меню выберите пункт Polygon. Вокруг сферы появляется прямоугольная полигональная оболочка.
228 Полигоны и поверхности разделения 5. Правой кнопкой мыши щелкните по сфере и в контекстном меню выберите пункт Face (Грань). Выделите грань на передней части полигона (рис. 8.93). 6. В меню Edit Polygons {Редактирование полигонов) выберите пункт Extrude Face (Выдавить грань). Уменьшите размеры грани (рис. 8.94). 7. В меню Edit Polygons повторно выберите пункт Extrude Face. Переместите грань вперед и вверх (рис. 8.95). Это шея черепахи. 8. Выполните команду меню Edit Polygons *$ Extrude Face. Пропорционально увеличьте грань (рис. 8.96).
Рис. 8.94. Размер грани уменьшен. Чтобы отобразить в центре грани манипулятор пропорционального масштабирования, щелкните по другому манипулятору масштабирования
9. В меню Edit Polygons выберите пункт Extrude Face. Переместите грань вперед (рис. 8.97). Это голова черепахи.
Рис. 8.95. Переместите грань вперед и вверх
Рис. 8.93. Выделена передняя грань
Рис. 8.96. Масштабирование этой грани определяет размер затылочной части головы черепахи
Моделирование поверхностей разделения
229
10. Выделите грань на нижней стороне: сферы. 11. В меню Edit Polygons выберите пункт Subdivide (Разбиение) - рис. 8.98. 12. Выполните команду меню Edit Polygons =£ Extrude Face. Пропорции' нально уменьшите размеры граней (рис. 8.99).
Рис. 8.97. Чтобы придать голове объем, переместите грань вперед
Рис. 8.98. Посмотрев на объект снизу, вы увидите, что нижняя часть была разделена
Рис. 8.99. Основания ног уменьшаются одновременно
13. В меню Edit Polygons выберите еще раз пункт Extrude Face. Переместите грани вниз (рис. 8.100). Модель черепахи готова.
Рис. 8.100. Переместите эти грани вниз, чтобы определить длину ног. Модель черепахи готова
230 Полигоны и поверхности разделения Моделирование телефонной трубки на основе полигонального примитива 1. В меню Create выберите пункт Polygon Primitives => Cube. 2. Уменьшите размеры куба в направлении оси Z так, чтобы он стал более плоским. Уменьшите его размеры в направлении оси X, чтобы сузить объект (рис. 8,101). 3. Правой кнопкой мыши щелкните по кубу и в контекстном меню выберите пункт Face. 4. Выделите верхнюю грань куба.
Рис. 8.102. Высота объекта увеличилась вдвое после выдавливания верхней грани
5. В меню Edit Polygons выберите пункт Extrude Face. Переместите грань вверх, чтобы удвоить высоту объекта (см. рис. 8.102). 6. Еще раз выполните команду меню Edit Polygons & Extrude Face. Переместите грань вверх таким образом, чтобы передняя часть объекта состояла из трех равных граней (рис. 8.103). 7. На передней части объекта выделите верхнюю и нижнюю грани. 8. В меню Edit Polygons выберите пункт Extrude Face. Переместите грани по оси Z (рис. 8.104).
Рис. 8.103. Теперь передняя часть объекта состоит из трех равных граней
Рис. 8.104. Переместите выдавленные поверхности по оси Z, чтобы придать объекту форму телефонной трубки Рис. 8.101. Полигональный куб стал плоским и узким
Моделирование поверхностей разделения 231 9. Нажмите клавишу F8, чтобы переключиться в режим выделения объектов (рис. 8.105). Объект должен быть выделен. 10. В меню Modify выберите пункты Convert => Polygons to Subdiv (Преобразовать => Полигоны в разделения) рис. 8.106. Модель телефонной трубки готова (рис. 8.107). Рис. 8.105. Телефонная трубка перед преобразованием в поверхности разделения. Режим выделения переключен на выделение объектов
Поверхности разделения можно преобразовать обратно в полигоны, выбрав пункть меню Modify 4> Convert => Subdiv to Polygon.
trensfcmrationTasts Reset T>an stamstio п в i=re в/ е Transform eti ons Snap ASigR Cbjeds E nettle Ngdes MefeeUue Center Pivot Prafe Hjerorchy NSHtiss .
Edrt-AJiribute.. Delete Attribute.
Выполнив команды меню Modify ^ Convert => NURBS to Subdiv, можно преобразовать поверхность NURBS в поверхность разделения. Следует запомнить, что преобразовывать в поверхности разделения допускается только простые формы, будь это NURBS или полигоны. Если поверх ность уже была детализирована, после преобразования с ней будет трудно работать, поскольку к ее точкам добавится ог ромное количество точек, создаваемых при разделении.
Рис. 8.10Б. Выполните команду меню Convert Polygons to Subdiv
Рис. 8.107. При преобразовании в поверхности разделения модель телефонной трубки стала гладкой и округлой
232 Полигоны и поверхности разделения Поверхности разделения обычно имеют гладкую и округлую форму. Для получения плоских областей и острых ребер следует использовать инструменты группы Crease (Излом).
Добавление частичного излома 1. Создайте телефонную трубку, следуя инструкциям предыдущего упражнения. Перейдите в стандартный режим, выполнив команду меню Subdiv Surfaces Standard Mode. 2. Правой кнопкой мыши щелкните по поверхности и в контекстном меню выберите пункт Edge. 3. Выделите восемь ребер в верхней части телефонной трубки (рис. 8.108). 4. В меню Subdiv Surfaces выберите пункт Partial Crease Edge/Vertex (Частичный излом ребра/вершины) - рис. 8.109. 5. Повторите шаги 3 и 4 для нижней части телефонной трубки. Теперь верхняя и нижняя части трубки имеют более плоскую, квадратную форму (рис. 8.110).
Рис. 8.108. Если камера правильна позиционирована, можно воспользоваться рамкой, чтобы ()ыстро выделить несколько ребер
Texture FuBCreHsel
Ичггог
дней!
Cotiapae Mlereichy Standard Mocte Polygon PTO^ode ConvesSeledsonTof'acss Con vert Selection To Eidges Convert SsteicnTo-Vsraee Convert Seteeflon TG LfV*
Добавление полного излома в вершины 1. Выполните команды меню Create c> Subdiv Primitives ^ Cylinder.
Reltne SeHSerad COB^anent Com a ponent Qieplfty Level pcnenf Display FHLar
Рис. 8.109
Это меню позволяет не только добавлять изломы в ребра, но и удалять изломы с помощью команды Uncrease Edge/Vertex
2. Масштабируйте поверхность по оси Y, увеличив начальную длину примерно в три раза. 3. Правой кнопкой мыши щелкните по поверхности цилиндра и в контекстном меню выберите пункт Vertex. 4. Выделите точку в середине верхней грани и переместите ее вверх. Рис. 8.110. В результате модель телефонной трубки стала болзе реалистичной
Моделирование поверхностей разделения 233 5. В меню Subdiv Surfaces выберите пункт Full Crease Edge/Vertex (Пол ный излом ребра/вершины). Верхняя точка станет острой (рис. 8.111). 6. Выделите нижний ряд точек с помощью рамки и уменьшите расстояние между ними.
Рис. 8.111. Выделенная точка перемещена вверх (слева), затем к ней применена команда Full Crease (справа)
7. Оставьте точки выделенными, щелкните правой кнопкой мыши по гюверхнос ти и в контекстном меню выберите пункт Refine. 8. Выделите четыре симметрично расположенные точки на нижней части поверхности (рис. 8.112). 9. В меню Subdiv Surfaces выберите пункт Full Crease Edge/Vertex. 10.Переместите точки вниз и масштабируйте их с уменьшением. Перед вами модель простого ракетоносителя (см. рис. 8.113).
Рис. 8.112. Выделите четыре точки, симметрично расположенные на нижней части объекта. Рекомендуется просмотреть объект в разных видах, чтобы убедиться, что выделены именно нужные точки
Рис. 8.113. Точки перемещены вниз и отодвинуты от центра пропорциональным масштабированием. Теперь они образуют опоры простого ракетоносителя
234 Полигоны и поверхности разделения Добавление полного излома в ребра 1. Создайте ракету из предыдущей задачи (рис. 8.114). 2. Правой кнопкой мыши щелкните по поверхности и в контекстном меню выберите пункт Edge. 3. Правой кнопкой мыши щелкните по поверхности и выполните команды Display Level ^ 0. 4. Правой кнопкой мыши щелкните по поверхности и в появившемся контекстном меню выберите пункт Edge.
Рис. 8.114. Ракетоноситель из предыдущей задачи
5. Выделите все вертикальные ребра. Чтобы избежать выбора горизонтальных ребер, выделите с помощью рамки вертикальные ребра в нижней части, затем, удерживая нажатой клавишу Shift, выделите ребра в средней и верхней части (рис. 8.115). 6. В меню Subdiv Surfaces выберите пункт Full Crease Edge/Vertex. Ребра ракеты стали острыми (рис. 8.116). Рис. 8.115. Чтобы избежать выделения горизонтальных ребер, нажмите клавишу Shift и выделите вертикальные ребра по одному
Рис. 8.116. Заострзние ребер придает ракете более интересную форму
(ШШ1
и оштш
ЛИШПИШ)
9 Наверное, вы захотите немедленно оживить смоделированный персонаж. Однако сначала нужно поместить внутрь персонажа скелет. Скелет представляет собой иерархию отдельных суставов, соединенных костями.
Рис. 9.1. Скелет этого персонажа, имеющего форму глазного яблока, используется для того, чтобы придавать модели различные позы ианимировать ее
Лучший пример размещения суставов предлагает природа. Воспользуйтесь изображениями скелетов человека или животно го (рис. 9.1). Плечевой сустав должен нахо дится в плече, локтевой - в локте и т.д. Од нако необязательно соблюдать такую точность. Например, в ступне человека двадцать шесть костей, но анимировать ступню можно с помощью трех. Во всех местах предполагаемого сгиба модели поместите сустав. Суставы связаны друг с другом отноше нием наследования, то есть нижние суставы перемещаются вслед за верхними суставами иерархии. Сустав, который вы создадите первым, окажется на верхнем уровне иерархии, его часто называют основным, или корневым (root joint),
Скелеты и обратная кинематика С помощью этого сустава перемещается весь скелет. Коленный, голеностопный суставы и сустав ступни находятся ниже тазобедренного, поэтому при повороте этого основного сустава двигается и вся нога. Анимация, производимая таким способом, называется прямой кинематикой (forward kinematics - FK) - рис. 9.2. При обратной кинематике (IK - inverse kinematics) анимация производится снизу вверх по уровням иерархии. Есчи вы перемещаете ступню, то колено и бедро повернутся соответствующим образом (рис. 9.3).
Суставы
Рис. 92. Здесь иллюстрируется принцип прямой кинематики: лрл повороте тазобедренного сустава все суставы, на мыши, сустав окажется на своем месте 5. Создание скелета завершено. Для отключения инструмента Joint нажмите клавишу Enter. Верхний сусгав скелета выделен, поэтому подсвечивается весь скелет.
Рис. 9.5. Создан второй сустав. Между двумя суставами появляется кость. Это означает, что они связаны отношением наследования. Кость возле сустава-предка расширяется
Строить скелет рекомендуется при вклю ченной сетке, чтобы все суставы были на дежно выровнены. Размещая суставы, удерживайте нажатой клавишу х. Можно увеличить или уменьшить размер отображения суставов в окнах видов, вы полнив команду меню Display о Joint Size (Отобразить с* Размер сустава) и выбрав процентный размер из списка. Чтобы удалить сустав, выделите его и нажмите клавишу Delete. Сустав будет удален вместе со всеми суставами, которые находятся на нижнем уровне иерархии. При построении скелета вам потребуется создать ветвь, исходящую из сустава в центре иерархии. Например, скелеты рук ответвляются от сустава грудной клетки.
238 Скелеты и обратная кинематика Ответвление существующего скелета 1. Создайте скелет, описанный в предыдущем примере. 2. Нажмите кнопку инструмента Joint J^, 3. Щелкните по суставу, от которого вы хотите создать ветвь. Выделится основной сустав. 4. Щелкните в том месте, где требуется поместить новый сустав. Появится новый сустав и кость, ответвляющаяся от ранее созданного скелета (рис. 9.6). 5. В меню Window выберите пункт Нуpergraph, чтобы просмотреть иерархию с помощью гиперграфа. Заметьте, что два сустава находятся на одном уровне иерархии и наследуются к одному и тому же суставу (рис. 9.7), Кости можно считать наглядным представлением связи в иерархии суставов скелета. Кость появляется, если вы присоединяете один сустав к другому отношением наследования. Если это отношение разрывается, то кость исчезает. Иногда проще создать отдельные иерархии, а затем собрать из них один скелет, связав их отношением наследования.
Рис. 9.6. Новый сустав ответвляется от ранее созданного скелета
Рис. 9.7. Узлы joints и joint4 являются потомками jointZ. Таким образом, если поворачивается сустав joint2, то вместе с ним поворачиваются joints и joinM
Наследование суставов 1. На виде сбоку создайте скелет ноги и ступни из пяти суставов (рис. 9.8), Нажмите Enter, чтобы завершить процесс создания.
Рис. 9.8. Скелет ноги включает в себя тазобедренный, коленный, голеностопный суставы, а также суставы стопы и пальца. Если персонаж носит ботинки, суставы для пальцев не нужны - в данном случае достаточно одной кости
Суставы
239
2. На виде сбоку создайте суставы позвоночника снизу вверх, связав их в отдельную иерархию (рис. 9.9). 3. На виде спереди передвиньте модель ноги в сторону,
Рис. 9.9. Суставы позвоночника создаются снизу вверх. Нижний сустав является предком остальных суставов, которые занимают нижние ступени иерархии, несмотря на то что на рисунке они находятся выше
4. Выделите верхний сустав ноги, а затем нажмите клавишу Shift и выделите нижний сустав позвоночника. Нажми те клавишу р. Между ногой и позво ночником появится кость. Это означа ет, что две отдельные иерархии соединились в одну (рис. 9.Ю). Таким же способом можно разорвать наследование между суставами. Выделите объект, который требуется отсоединить, и нажмите клавиши Shift+p. Сустав больше не связан отношением наследования, а кость исчезает. Создав одну ногу или руку персонажа, вы можете зеркально отобразить суставы, чтобы сэкономить время, и скопированная нога или рука появится на другой стороне тела модели.
Рис. 9.10. Нога наследуется к позвоночнику. Теперь нижний сустав скелета является основным для всего персонажа. Если этот сустав перемещается, перемещается и весь персонаж
240 Скелеты и обратная кинематика Зеркальное отображение суставов 1. Выделите скелет ноги, созданный в предыдущем примере. 2. Выделите тазобедренный сустав (см. рис. 9.11). 3. В меню Skeleton щелкните по значку рядом с пунктом Mirror Joint. Откроется диалоговое окно Mirror Joint Options (Настройка зеркального отображения сустава). 4. В разделе Mirror Across (Плоскость отображения) выберите переключатель YZ (рис. 9.12). 5. Нажмите кнопку Mirror. К скелету будет присоединена вторая нога (рис. 9.13). Если скелет ноги создан на виде сбоку, зеркально отображать его нужно в плоскости YZ. Чтобы понять, какую плоскость следует использовать, посмотрите на значок осей в углу окна вида. Представьте себе две оси, образующие плоскость, относительно которой вы хотите зеркально отобразить суставы. Если скелет зторой нога находится в неправильном положении, отмените зеркальное отображение сустава и попытайтесь выбрать в диалоговом окне Mirror Joint Options нужную плоскость для отображения. Не отображайте зеркально сустав, который находится на плоскости симметрии персонажа. Иначе вы получите два сустава, расположенных друг на друге. Когда вы перемещаете сустав, все суставы, находящиеся на нижних уровнях иерархии, двигаются вместе с ним. Сустав можно переместить независимо от его положения в иерархии, воспользовавшись режимом перемещения центра трансформаций.
Рис. 9.11. Выделен тазобедренный сустав - теперь скелет ноги можно зеркально отобразить О @ _С5> Ed«
___
__
_Mirrpf
РЧ-i;
Mirror А< о 51 ^ XY
ft
Mirror funaan g B*ha,,ior Mirror
Apply
YZ
Qxz О Orientation dost
Рис. 9.12. Выбран переключатель YZ, поэтому скелет ноги будет зеркально отражен относительно плоскости YZ
Рис. 9.13. Вторая нога будущего персонажа создана с помощью диалогового окна Mirror Joint Options, вызываемого из меню Skeleton
Суставы
241
Перемещение сустава 1. Создайте скелет, описанный в предыдущих примерах. 2. Выделите коленный сустав (рис. 9.14). 3. Нажмите клавишу w. 4. Переместите колено назад. Голень и стопа передвинутся вместе с ним (рис. 9.15), 5. Нажмите клавишу z, чтобы отменить последний шаг. Рис. 9.14. Выделите коленный сустав ноги
6. Нажмите клавишу Insert/Home, чтобы перейти в режим перемещения центра трансформаций. 7. Переместите колено назад. Голень и стопа остаются на месте (рис. 9.16). 8. Нажмите клавишу z, чтобы отменит], последний шаг. Нажмите еще раз клавишу Insert/Home, чтобы выйти из ре жима перемещения центра трансфер маций.
Рис. 9.15. При перемещении колена голень и стопа передвигаются вместе с ним. Заметьте, что кость между тазом и коленом становится длиннее
Рис. 9.16. Если передвигать коленный сустав в режиме перемещения центра трансформаций, то ступня, которая находится ниже колена в иерархии, остается на месте
16 Э-81
242 Скелеты и обратная кинематика Вставка сустава 1. Создайте скелет с несколькими суставами (рис. 9.17). 2. В меню Skeleton выберите пункт Insert Joint Tool {Вставить сустав). 3. Щелкните по суставу и перетащите новый сустав. Новый сустав будет добавлен в иерархию между суставом, по которому вы щелкнули, и суставом, находящимся на нижней ступени. Проще всего это делать в одном из ортогональных видов (рис. 9.18).
Рис. 9.17. В ортогональном виде создан скелет с несколькими суставами
4. Нажмите клавишу Enter, чтобы завершить процедуру и закрыть инструмент. Иногда, внимательно рассмотрев скелет в окнах проекций, вы обнаруживаете, что создали больше суставов, чем требовалось. В этом случае можно выделить сустав и удалить его из иерархии, не удаляя узлы, занимающие нижние ступени иерархии, как произошло бы при обычном удалении сустава.
Удаление сустава из иерархии 1, Щелчком мыши выделите сустав, который требуется удалить (рис. 9.19).
Рис. 9.18. Между двумя существующими суставами создан новый. Он помещен между суставами как в окне проекции, так и в иерархии
2. В меню Skeleton выберите пункт Remove Joint (рис. 9.20). Сустав удален из иерархии и со сцены. После удаления выделенного сустава его предок соединяется костью с его потомком (рис. 9.2]). В некоторых случаях вам потребуется отсоединить часть созданного ранее скелета и использовать его в новом персонаже, например, при создании кентавра, верхняя часть которого является человеческим телом, а нижняя - животным. Отсоединив центральный сустав, вы можете использовать верхнюю часть скелета человека.
Рис. 9.19. Выделите сустав, щелкнув по нему в окне проекции Dope Sheet (Окно ^ Редакторы анимации ^ Монтажный стол) - рис. 11.50. Вы увидите три сустава и отображение ключевых кадров. 8. Щелкните по пункту joint2 (Сустав2) в левой части окна Dope Sheet. На пра вой панели окна Dope Sheet будут выделены ключевые кадры для второго сустава. 9. Удерживая нажатой среднюю кнопку мыши, перетащите ключевые кадры на три кадра вправо (рис. 11.51). Рис. 11.50. Выберите пункт меню Dope Sheet Editor
10. Щелкните по пункту joint3 в левой части окна Dope Sheet. П.Удерживая нажатой среднюю кнопку мыши, перетащите ключевые кадры на шесть кадров вправо, 12. Выберите все три сустава в левой части окна Dope Sheet. 13. Выполните команды меню Curves ^> Рге Infinity ^ Cycle (Кривые => До основного фрагмента ^> Цикл) - см. рис. 11.52.
Рис. 11.51. С помощью средней кнопки мыши перетащите ключевые кадры для второго сустава
14. Выберите пункты меню Curves ^> pOst Infinity ^> Cycle (Кривые ^ После основного фрагмента => Цикл). Теперь созданная вами модель имитирует движения махающего хвоста с цикличностью и смещениями, 15.Нажмите на кнопку Play (Просмотр), чтобы воспроизвести анимацию,
Рис. 11.52. Выберите пункт меню Рге Infinity или Post Infinity, затем щелкните по пункту меню Cycle, чтобы создать циклическую анимацию, которая будет повторять анимацию, заданную ключевыми кадрами
294 Анимация
Ограничения В реальной жизни движение объектов ограничено тем или иным способом. Рассмотрим такой пример: глаза теннисиста постоянно следят за движением мяча. Если бы потребовалось воспроизвести движения мяча и глаз, создав для них ключевые кадры, мы потратили бы много времени и сил. Для решения подобной анимационной задачи следует воспользоваться функциями ограничения. Ограничения (constraint) связывают определенные атрибуты объектов. Например, требуется, чтобы один объект повторял все повороты (rotate) другого, но при этом они перемещались (translate) различным образом. Функции ограничения позволяют связать значения вращения двух объектов, а все остальные атрибуты оставить неизменными (то есть ограничить связь объектов вращением). Все ограничения работают одинаково: вы выделяете два объекта или более, затем выбираете тип накладываемого ограничения. Объект-мишень, выделенный первым, становится ограничителем, а второй - ограничиваемым. Ограничения также могут быть анимированы и включены/отключены, что позволяет связывать атрибуты временно.
Типы ограничений Maya предлагает следующие типы ограничений: • Point (Точечное) соединяет центр ограничиваемого объекта с центром объектамишени; • Orient (Ориентация) связывает вращение одного объекта с вращением другого, при этом параметры поворота ограничиваемого объекта точно соответствуют повороту мишени;
Scale (Масштабирование) присваивает ограничиваемому объекту те же параметры масштабирования, что и мишени, или их среднее значение, если объектов-мишеней несколько; Aim (Цель) нацеливает один объект на другой. В результате применения данной функции создается вектор цели (по умолчанию его положение совпадает с осью X объекта), задающий для ограничиваемого объекта положение мишени. Это ограничение может использоваться, например, для того, чтобы указать направление взгляда персонажа; Parent (Наследуемое) является новшеством пятой версии Maya. Оно действует аналогично функции наследования, но позволяет при этом сместить зависимый объект относительно главного. Допускается активировать/отключать данное ограничение, а также выбирать, какие атрибуты будут задействованы, что невозможно при использовании команды наследования; Geometry (Геометрическое) ограничивает положение одного объекта поверхностью другого объекта. Центр трансформаций ограничиваемого объекта остается на поверхности мишени. При этом его атрибуты не блокируются, что позволяет ему скользить вдоль поверхности мишени; Normal (По нормали) по принципу действия сходно с ограничением Aim. Разница лишь и том, что вектор цели ограничиваемого объекта направлен вдоль нормали к поверхности, П|юходящей через центр ограничиваемого объекта; Tangent (По касательной) ограничивает ориентацию объекта согласно направлению кривой. Если ограничиваемый
Ограничения 295 Constrain
«го p Bend (Создать нелинейный деформатор => Изгиб) - рис. 12.2. К выделенной поверхности будет применен деформатор Bend. 3. Щелкните по заголовку Bend в разделе Inputs (Входные данные) окна Channel Box (Редактор каналов), чтобы просмотреть свойства деформатора Bend (рис. 12.3).
Рис. 12.3. В свойствах деформатора Bend указано, насколько сильно должен деформироваться объект
Нелинейные деформаторы 313 INPUTS bendl tweak! m a k E Nurb Су 11 n d н г1 Envelope 1 Curvature 1
4. Поставьте в поле Curvature значение 1, Теперь объект будет изгибаться вокруг своего геометрического центра. 5. Присвойте параметру Low Bound зна чение 1. Изгиб объекта вокруг центра сохранится, но будет изгибаться только его верхняя часть (рис. J2.4). Для получения различных эффектов можно перемещать деформаторы относительно объектов или вращать их.
Рис. 12.4. Параметр Curvature определяет величину изгиба объекта, a Low Bound - положение точки изгиба относительно его нижней части. Если параметр Low Bound задан равным 0, то нижняя половина цилиндра остается неизменной (показано на рисунке), а если Low Bound задан равным -1. то вся нижняя часть цилиндра будет деформирована Деформатор
Цилиндр
Деформатор Flare Деформатор Flare позволяет создать выпуклую или суженную поверхность, что особенно полезно при работе с такими объектами, как вазы, заготовки фигур персонажей и колокола. Деформатор Flare имеет следующие параметры: • Start Flare X и Z (Начать деформацию по осям X и Z) определяет величину деформации поверхности в начале нижней границы вдоль указанной оси; • End Flare X и Z (Закончить деформацию по осям X и Z) задает величину деформации в начале верхней границы вдоль указанной оси; • Curve (Кривая) определяет величину кривизны перехода между границами Low и High Bound.
Использование деформатора Flare Рис. 12.5. Вы можете контролировать внешний вид деформации с помощью особого манипулятора. Цилиндр на рисунке окрашен в серый цвет, адеформатор-в белый
1. Выделите объект для деформации. 2. Выберите в меню Deform пункты Create Nonlinear => Flare (Создать нелинейный деформатор ^ Выпуклость}. К выделенной поверхности будет применен деформатор Flare - рис. 12.5.
314
Деформаторы
3. Щелкните по заголовку Flare под разделом Inputs в окне Channel Box, чтобы просмотреть свойства деформатора Flare, 4. Выберите строку Start Flare X (см. рис. 12.6). 5. Перетащите указатель с помощью средней кнопки в окне Perspective, изменяя диаметр основания объекта до тех пор, пока параметр Start Flare не будет равен 3. В нижней части объекта появится раструб (рис. 12.7).
Рис. 12.6. Параметры деформатора Flare
Рекомендуется заранее подготовить геометрию поверхности к деформации: добавить нужное количество контрольных точек и изопармов. Если вы решите дополнить геометрию уже после использования деформатора, это приведет к нежелательным результатам. Поверхность проигнорирует деформатор или преувеличит его эффект.
Деформатор Sine Деформатор Sine изгибает объект по заданной синусоиде. Он имеет следующие параметры: • Amplitude (Амплитуда) определяет максимальное значение амплитуды для синусоиды; • Wavelength (Длина волны) задает частоту волны. При уменьшении данного параметра частота волны увеличивается, при увеличении - уменьшается; • Offset (Смещение) определяет положение синусоиды относительно центральной точки манипулятора (handle) деформации;
Рис. 12.7. Деформатор Flare создает расширяющийся объект
Нелинейные деформаторы 315] • Dropoff (Затухание) задает изменение амплитуды синусоиды по мере удаления от центра. При отрицательном значении параметра амплитуда затухает по направлению к центральной точке манипулятора деформации, при положительном значении - в противоположном направлении,
ЕЖ Membership Tod Prune Membershp
Использование деформатора Sine 1. Выделите объект для деформации. Рис. 12.8. Чтобы применить деформатор к поверхности, выберите пункт меню Sine tHPllTS
•Jiiel Amplilmte J c'
iffli
OSaet'] IBSD
nd[l I
2. Выберите в меню Deform пункты Create Nonlinear =£• Sine (Создать нелинейный деформатор =* Синусоида) рис. 12.8. К выделенной поверхности будет применен деформатор Sine. 3. Щелкните по заголовку Sine под разделом Inputs в окне Channel Box, чтобы просмотреть свойства деформатора Sine. 4. Щелкните по строке Amplitude.
Рис. 12.9. Деформатор Sine придает объекту волнообразную форму
5. Перетаскивайте указатель с помощью средней кнопки в окне вида Perspective до тех пор, пока параметр Amplitude не станет равен 0,5. Форма объекта будет изменена. 6. Щелкните по строке Wavelength, 7. Чтобы увеличить кривизну деформации, перетаскивайте указатель с помощью средней кнопки в окне вида Perspective до тех пор, пока параметр Wavelength не будет равен I (рис. 12.9).
316
Деформаторы
Деформатор Wave Деформатор Wave идеально подходит для создания концентрических колец на воде, возникающих при падении капли, а также небольших волн на поверхности. Лучшие результаты достигаются при изменении детализированных плоских поверхностей. Деформатор Wave имеет следующие настройки: • Amplitude определяет максимальное значение амплитуды волны; •
Wavelength указывает частоту волны. При уменьшении данного параметра частота увеличивается, при увеличении - уменьшается;
• Offset задает положение синусоиды относительно центральной точки манипулятора деформации. При анимации параметра Offset поверхность будет пульсировать; • Dropoff определяет, как должна меняться амплитуда волны по мере удаления от центра. При отрицательном значении параметра амплитуда затухает по направлению к центральной точке манипулятора деформации, при положительном значении - увеличивается; • Dropoff Position (Положение затухания) задает начальное и конечное значения амплитуды волны; • Min and Max Radius (Минимальный и максимальный радиус) указывает минимальный и максимальный радиусы круговой синусоидальной волны.
Нелинейные деформаторы 317 Деформатор
Использование деформатора Wave 1. Создайте плоскость NURBS. 2. Присвойте параметрам Patches U и Patches V значение 10 в окне Channel Box. 3. Выберите в меню Deform пункты Create Nonlinear £> Wave (Создать нелинейный деформатор => Волна). К выделенной поверхности будет применен деформатор Wave - рис. 12.10
Плоскость
Рис. 12.10. Манипулятор Wave контролирует параметры деформатора Wave. Деформатор окрашен в белый цвет, а плоскость - в серый
4. Щелкните по заголовку Wave под разделом Inputs в окне Channel Box, чтобы просмотреть свойства деформатора Wave. 5. Установите параметр Amplitude ранным 0,6. Объект изогнется в форме волны (рис. 12.11). 6. Задайте значение Wavelength равным 1,4. Количество волн на поверхности уменьшится (рис. 12.12).
Деформатор Squash Рис. 12.11. Параметр Amplitude определяет максимальную амплитуду волны
Рис. 12.12. При увеличении параметра Wavelength до 1,4 частота волны уменьшается
Деформатор Squash вытягивает или сплющивает объект. Если вы масштабируете поверхность по вертикали вдоль одной оси, оставляя ее неизменной вдоль других осей по горизонтали, вы создаете поверхность с меньшим физическим объемом. Однако при этом объект перестает быть похожим на свой реальный прототип, который всегда сохраняет объем при сплющивании. Чтобы объекты деформировались более естественно, следует сохранять объем прежним при сплющивании и растяжении.
318 Деформаторы Деформатор Squash имеет следующие настройки:
••
• Factor (Степень) задает значение сплющивания или растяжения объекта; • Expand (Расширение) определяет, насколько объект будет расширяться в объеме при сплющивании или сужаться при растяжении; •
Start and End Smoothness (Начальное и конечное сглаживание) указывает величину сглаживания (по аналогии с параметром Dropoff) рядом с нижней границей (Start Smoothness) или верхней границей (End Smoothness). В цилиндре, например, верхней и нижней границами считаются верхнее и нижнее основания. Если вы увеличиваете параметр Start Smoothness, то точки в нижней части цилиндра будут более плавно переходить в область сплющивания.
Create Jiggle Defonar Create iggte о* с* ле
Рис, 12.13. Выберите в меню Detorm пункты Create Nonlinear => Squash
Использование деформатора Squash 1. Создайте цилиндр NURBS, 2. Выберите в меню Deform пункты Create Nonlinear ^> Squash (Создать нелинейный деформатор £> Сплющивание) - рис. 12.13. К выделенной поверхности будет применен деформатор Squash.
Рис. 12.14. Отрицательное значение параметра Factor сплющивает объект, положительное вытягивает
3. Щелкните по заголовку Squash под разделом Inputs в окне Channel Box, чтобы просмотреть свойства деформатора Squash. 4. Установите параметр Factor равным -0,7. Объект будет сплющен по вертикали (рис. 12.14). 5. Задайте значение Expand равным 1,7. Теперь объект расширится в объеме (рис. 12.15).
Рис. 12.15. После сплющивания необходимо расширить объект, чтобы сохранить начальный объем
Нелинейные деформаторы 319 Деформатор Squash может быть помещен в ключевой кадр для анимации сплющивания/растяжения объекта или персонажа.
Деформатор Twist Деформатор Twist (Скручивание) часто используется для того, чтобы преобразовать куб в здание «мультяшного» вида или для создания изогнутой металлической конструкции. Чем выше плотность поверхности объекта, тем более гладким будет изгиб. Рис. 12.16. При изменении значения параметра End Angle поверхность объекта скручивается
End Law Bound 0 High Bound I
Действие деформатора Twist определяется параметрами Start Angle (Начальный угол) и End Angle (Конечный угол), которые задают угол скрутки на нижней и верхней границах.
Использование деформатора Twist 1. Создайте полигональный куб. 2. Выберите в меню Deform пункты Create Nonlinear => Twist (Создать нели нейный деформатор "=> Скручивание). К выделенной поверхности будет применен деформатор Twist.
Рис. 12.17. Присвойте параметру Low Bound значение О, чтобы начать скручивание объекта с его средней части
3. Щелкните по заголовку Twist под разделом Inputs в окне Channel Box, чтобы просмотреть свойства деформатора Twist. 4. Установите параметр End Angle равным 40. Объект скручивается относительно центра манипулятора деформации (рис. 12.16). 5. Задайте значение Low Bound равным 0. Теперь скручивание объекта начинается с его средней части (рис. 12.17).
320 Деформаторы
Деформатор Lattice Деформатор Lattice (Решетка) - один из наиболее используемых и самых функциональных деформаторов Maya. Он упрощает выделение контрольных точек на поверхности и позволяет управлять деформацией сложных объектов при помощи меньшего числа вершин, чем при непосредственной модификации модели. С помощью решетки вы можете создавать выпуклости на локте персонажа н контролировать вид поверхности в областях, где она должна иметь излом (например, в локтях и коленях). Когда вы применяете деформатор Lattice к объекту, Maya создает вокруг объекта особый контейнер в форме параллелепипеда, который и называется решеткой (рис. 12.18). При трансформации решетки или ее вершин (перемещения, вращения или масштабирования) объект внутри нее меняет свою форму (рис. 12.19). Форму решетки (а значит, и объекта) можно изменять, используя другие деформаторы. Важным параметром деформатора Lattice является Divisions (Разделения), который находится в узле Lattice's Shape (Форма решетки) в окне Channel Box. Деформатор Lattice является одним из немногих объектов Maya, параметры которого доступны в узле Shape. При увеличении плотности решетки число ее вершин, которые можно выбрать и использовать для деформации объекта, также увеличивается. Это объясняется тем, что на каждом пересечении граней решетки создается вершина, или точка решетки.
Рис. 12.18. Решетка используется для деформации сферы NURBS
Рис. 12.19. Перемещая точки решетки, вы деформируете поверхность объекта
Деформатор Lattice 321 Deform
Skeleton
Skin
Constrain
c\
1. Создайте сферу NURBS.
Edit Membership Tool Prune Membership
2. Выберите в меню Deform пункт Create Lattice (Создать решетку) — рис. 12.20. К выделенной поверхности будет применен деформатор Lattice.
Create Blend Shape Edit Btend Shape Create Lattice Edit Lattice
Г)
Рис, 12.20. Чтобы окружить объект решеткой, выберите пункт меню Create Lattice
Рис. 12.21. Чтобы отобразить точки решетки, установите режим выделения Pick Mask как Select by component type Решетка
Использование деформатора Lattice
3. Установите режим выделения Pick Mask как Select by component type (Вы деление компонентов) - рис. 12.21. На экране отобразятся все точки решетки, 4. Выберите угловую точку решетки (см. рис. 12.22). 5. Переместите точку решетки (рис. 12.23). Поверхность будет деформирована в соответствие с изменением формы решетки.
Сфера
Рис. 12.23. Одна точка решетки перемещает несколько контрольных точек на поверхности
Точки решетки
Рис. 12.22. В каждой точке пересечения граней решетки появится точка решетки
21 Э-81
322 Деформаторы
Деформаторы Wire и Sculpt Деформаторы Wire (Каркас) и Sculpt (Формирование рельефа) используют объекты и кривые для манипуляции точками и деформации выделенной поверхности. Деформатор Wire использует одну или несколько кривых NURBS, которые называются каркасами, для деформации выделенной поверхности (рис. 12.24). Ограничить область влияния данного деформатора можно с помощью дополнительных кривых, которые называются опорами. Они позволяют точно управлять деформацией очень маленьких поверхностей. Деформатор Sculpt в качестве основного приспособления для деформации поверхности использует сферический объект влияния, который создает рельеф округлой или кольцеобразной формы. Данный манипулятор (манипулятор деформации, имеющий форму сферы) называется сферой рельефа (рис. 12.25). Деформатор Sculpt можно применять для достижения различных целей. В частности, при моделировании лица с его помощью легко добиться эффекта скругления поверхности, например, на кончике носа или подбородке персонажа. Деформатор может работать в трех режимах: Flip (Обращение), Project (Проекция) и Stretch (Растяжение), позволяющих добиться различных эффектов.
Рис. 12.24. Для деформации плоской поверхности используется один каркас Плоскость
Деформатор
Рис. 12.25. Плоская поверхность была деформирован,* при помощи объекта влияния деформатора Sculpt. Деформатор имеет белый цвет, а плоскость - серый
Деформаторы Wire и Sculpt 323 Создание деформатора Wire без фиксатора 1. Создайте плоскость NURBS и присвойте параметрам Patches U и Patches V значение 10 в окне Channel Box (рис. 12.26).
Рис. 12.26. Для данной плоскости NURBS в полях Patches U и Patches У были заданы значения 10. Чем больше эти значения, тем более гладкой будет поверхность после деформации
2. Создайте на плоскости кривую NURBS (рис. 12.27}. Она будет использоваться в качестве манипулятора деформации, имеющего форму каркаса. Подобный манипулятор называют каркасом влияния. 3. Выберите в меню Deform пункт Wire Tool (Инструмент каркаса) - рис. 12.28. 4. Выделите плоскость и нажмите клавишу Enter. 5. Выделите кривую, созданную на основе контрольных точек, и нажмите клавишу Enter.
Create Blend Shape Ed:t Blend Shape Create Lattice Edit Lattice
Рис. 12.27. Наложение каркаса на поверхность определяет область деформации
CreateSoilptOeformer Create liggle Defcrmef Create Iggle Disk Cache Jiggle Disk Cache Attttstttes..
We Dropoff LQCatS
Рис. 1228. Чтобы определить поверхность для деформации и каркас влияния, выберите инструмент Wire Tool
324
Деформаторы
6. Переместите кривую по оси Y. Плоскость будет деформирована по контуру кривой (рис. 12.29). Чтобы более точно управлять процессом деформации поверхности, вы можете перемещать контрольные точки по любой оси, Если вы хотите, чтобы кривая деформировала меньшую по площади область, уменьшите значение параметра Dropoff Distance (Расстояние затухания).
Рис. 12.29. Форма кривой определяет деформацию поверхности
Создание деформатора Wire с фиксатором 1. Создайте плоскость NURBS и присвойте параметрам Patches U и Patches V значение К) в окне Channel Box. 2. Создайте кривую NURBS, которая лежит на плоскости. Она будет использоваться Б качестве каркаса. 3. Создайте фиксатор - окружность NURBS, которая лежит на плоскости (рис. 12.30). 4. В меню Deform щелкните по значку рядом с пунктом Wire Tool. 5. Отметьте флажок Holders (Фиксаторы) — рис, 12.31. 6. Щелкните по кнопке Close (Закрыть). 7. Выберите плоскость и нажмите клавишу Enter. 8. Выделите кривую, созданную на основе контрольных точек, и нажмите клавишу Enter. 9. Выберите окружность NURBS и нажмите клавишу Enter. 10. Переместите кривую по оси Y. Плоскость деформируется по контуру кривой, однако область воздействия деформатора ограничивается окружностью (рис. 12.32).
Рис. 12.30. Масштабируйте окружность до тех пор, пока она не займет большую часть плоскости
4Jf Wire Tool _»j Wire Settings P Haiders Envelope QomgEfea Local Influence Dropoff Distance Deformation Drdsi Default
-ж]
Рис. 12.31. Если отмечен флажок Holders, вы можете использовать дополнительную кривую, чтобы ограничить область воздействия деформатора Wire
Деформаторы Wire и Sculpt 325 Создание деформатора Sculpt 1. Создайте плоскость NURBS и присвой те параметрам Patches U и Patches V значение 10 в окне Channel Box. 2. Установите масштаб по осям X, Y и 7. равным 5. Масштабирование плоскости необходимо для того, чтобы деформатор не превышал ее размеров. 3. Выберите в меню Deform пункт Create Sculpt Deformer (Создать реформатор Sculpt). К объекту будет применен деформатор Sculpt (рис. 12.33). Рис. 12.32. Плоскость деформируется по контуру кривой, однако плоскость, лежащая за окружностью, не подвержена деформации
4. Выделите область поверхности, подвергшуюся деформации Sculpt, и пере местите ее в положительном направлении по оси Y. Деформатор Sculpt рас ширит исходную геометрию объекта (рис. 12.34). Вы можете выделить и переместить локатор (пересечение двух коротких прямых), чтобы определить направление действия деформатора Sculpt.
Рис. 12.33. Деформатор Sculpt выталкивает геометрию поверхности вокруг своей сферической формы влияния. При этом создается эффект, который напоминает падение тяжелого мяча в грязь
Рис. 12.34. Поверхность деформируется вокруг области воздействия десрорматора Sculpt
326 Деформаторы
Скрытие, отображение и удаление деформаторов
Деформатор
Цилиндр
Удаление деформатора 1. Выделите манипулятор деформатора, который требуется удалить (рис. 12.35). 2. Выберите пункты меню Edit Ф Delete (Редактировать ^> Удалить) или нажмите клавишу Backspace.
Удаление деформатора с сохранением деформации поверхности
Рис. 12.35. Выбран манипулятор деформатора Taper, который соединен с цилиндром
1. Выделите весь объект вместе с деформатором, который требуется удалить (рис. 12.35). 2. Выберите пункты меню Edit => Delete by Type ^ History (Редактировать ^ Удалить по типу ^ История). Деформатор будет удален, но деформация объекта сохранится неизменной,
Отобразить все деформаторы Выберите в меню Display (Отобразить) пункты Show !=> Show Deformers ^> All (Отображение ^> Показать деформаторы с> Все) - рис. 12.36.
Скрыть все деформаторы
Рис. 12.36. Выполните команды меню Display, чтобы отобразить все ранее скрытые деформаторы
Выберите в меню Display пункты Hide ^> Hide Deformers => АД (Скрыть ^ Скрыть деформаторы => Все) - рис. 12.37. Меню Display позволяет отдельно отобразить деформаторы определенного типа, например, решетки, объекты Sculpt, манипуляторы кластеров и нелинейных деформаторов. Рис. 12.37. Выпопните команды меню Display, чтобы скрыть все деформаторы
13 осщш Реалистичность трехмерной сцене придает тщательно подобранное освещение. Впечатление от едены во многом определяется ее освещением. Слишком сильное освещение делает сцену плоской, при этом зритель как бы находится вне действия, и интерес к происходящему на экране резко падает. Правильная установка интенсивности света и положения источника освещения позволяет скрыть недостатки модели или даже превратить их в достоинства. Вы можете использовать свет для привлечения внимания к определенному месту на сцене (рис. 13.1) или объекту, который вы желаете специально выделить (рис. 13.2). Источник света используется не только для освещения пространства, но и для создания теней и, что еще более важно, глубины изображения. Интенсивный свет формирует острые, четкие тени, мягкий свет - мягкие и плавные. Умение сочетать источники света и цвет освещения имеет очень большое значение. Это определяет настроение, передаваемое изображением, подчеркивает пространство и даже имитирует течение времени.
Рис. 13.1. Внимание зрителя фокусируется на освещенной области
Рис. 13.2. Правильное освещение помогает сделать акцент на определенном объекте
328 Создание освещения Веками художники использовали игру света и тени, чтобы пробудить эмоции зрителя. Леонардо да Винчи, Геррит ван Хонтхорст, Луиджи Караваджио экспериментировали с освещением на своих полотнах. В настоящее время аналогичные методы используются в кино. Примерами могут служить фильмы «Бегущий по лезвию бритвы», «Крестный отец» и «Привидение». Действие в этих фильмах поддерживается освещением с применением таких приемов, как изменение цветов, интенсивности и положения источников света.
Рис. 13.3. Освещение позволяет создать особое настроение, например, загадочное и пугающее
Управление источниками света может быть сложным и отнимать много времени. Прочитав данную главу, вы получите некоторые навыки этого непростого мастерства.
Создание настроения Прежде всего вам нужно подумать о том, в какое время дня разворачиваются события на вашей сцене. Освещение может создавать совершенно различные и порою неожиданные эффекты. Чтобы убедиться в этом, попробуйте в одной и той же сцене использовать три или четыре варианта освещения. На рис. 13.3 с помощью света создано настроение пугающей таинственности, а на рис. 13.4 эта же сцена ярко освещена, что придает ей радостное ощущение летнего утра.
Рис. 13.4. А этот вариант освещения создает настроение свежего летнего утра
Создание настроения
329
Ниже рассматриваются виды освещения, характеризующие разное время суток: • рассвет (dawn). Большая часть неба заполнена светом. Свет мягкий и рассеянный, поэтому объекты в комнате освещены слабо. Сначала становятся видимыми блики и отражения, затем постепенно прорисовывается все остальное. Рассвет характеризуется очень слабым светом, к которому человеческим глазам нужно некоторое время привыкать; • восход солнца (sunrise). Свет пробивается в комнату. Длинные тени и световые узоры проецируются на стену через окно, рассеивая свет по всей комнате. По мере того как солнце поднимается, тени становятся короткими и более прозрачными. Освещение преобразуется в яркий дневной свет; • закат солнца (sunset). Оранжевый, красный и розовый света заката заполняют облака и небо, создавая чувство спокойствия. День близится к завершению. Силуэты гор и деревьев выделяются на горизонте, на земле лежат длинные тени; • вечер (evening). Комнат}' заполняет мирный серебряно-синий свет. Освещение мягкое. Комната освещена свечами и потолочными лампами, свет которых быстро теряется в темноте. Естественное освещение - это свет луны, который создает голубоватые отблески по всей сцене.
330 Создание освещения
Редактор Hypershade Редактор Hypershade (Гипертонировщик) работает по тому же принципу, что и Нуpergraph, однако его возможности гораздо шире. Он позволяет создавать, удалять, просматривать и изменять источники освещения, а также работать с материалами и текстурами (рис. 13.5).
Открытие окна Hypershade Выберите пункты меню рабочего окна Panel "=> Panels => Hypershade (Панель ^> Панели с> Гипертонировщик);
или Щелкните по кнопке Hypershade/Persp (Гипертонировщик/Перспектива), находящейся под панелью инструментов в левой части окна;
или Выберите пункты меню Window •=> Rendering Editors => Hypershade (Окно О Редакторы визуализации => Гипертонировщик), Левую часть окна Hypershade занимает панель Create (Создать) -рис. 13.6. На ней размещаются узлы для работы с освещением и текстурами. С помощью средней кнопки мыши вы можете создать новый узел, перетащив значок из панели Create в рабочую область, расположенную справа.
Рис. 13.5. Окно редактора Hypershade Create АН Node; у Surface Aiiisotropic Blinn Lambert Lwered Shader
Phong E Harnp Shader Stiading Map Surface Shader
О •
U»e Background
Рис. 13.6. Панель Create
Редактор Hypershade Create Lights Т LJshts JJ^J. Ambient Light Area Light Directional Light Point Light Spot Light Volume Light
Рис. 13.7. При выборе опции Create Lights нз панели Create отображаются только источники освещения
Рис. 13.8. Вкладка Lights отображает два созданных источника освещения и рабочую область
331
Maya позволяет отображать в списке узлы только одного типа и скрывать все остальные. Чтобы определить тип узла и сократить список, щелкните по кнопке Create Textures (Создать текстуры) в верхней части панели Create и выберите в меню тип узла. Например, если указать опцию Create Lights (Создать источники освещения), то на панели Create будут отображаться только типы источников освеще ния (рис, 13.7). Чтобы просмотреть созданные узлы, следует перейти на одну из вкладок окна Hypershade: Materials (Материалы), Тех lures (Текстуры), Utilities (Утилиты)., Lights (Источники освещения), Cameras (Камеры) и Projects (Проекции). Любой созданный узел отображается на соответ ствующей вкладке или в выпадающем меню. Например, на вкладке Lights мож но одновременно увидеть направленный и точечный источники освещения откры той сцены (рис. 13.8), Под вкладками, которые задают тип узла., находятся вкладки Work Area {Рабочая область) и Shader Library (Библиотека тонировщиков). На вкладке Work Area вы можете присоединять атрибуты узлов, просматривать все соединения, а также задавать отображение только того источника света или текстуры, над которыми вы в данный момент работаете. Вкладка Shader Library содержит готовые наборы тонировщиков, включая тонировщики для зданий, еды, посуды и других распространенных объектов {библиотека Shader Library должна инсталлироваться отдельно с установочного диска Maya). Эти наборы часто служат основой для создании новых тонировщиков. В этой главе описывается работа с источниками света в окне Hyperhsade и на панели Create.
332 Создание освещения
Установки визуализации В Maya есть много способов достижения одного и того же результата. Рассмотрим некоторые установки, позволяющие значительно упростить работу. Для создания финальной визуализации используются три окна: Hypershade, Render View (Просмотр визуализации) и Camera View (Вид из камеры), который обеспечивает просмотр сцены спереди, сверху, сбоку, в перспективе или с любой созданной вами произвольной камеры. Один из способов подготовить сцену к визуализации - это выбрать разметку Hypershade/ Render/Persp в контекстном меню верхней части Hotbox - рис. 13.9. Рабочая область будет разделена на три окна: Hypershade (в верхней части экрана), Render View (слева) и Perspective (справа) - см. рис. 13.10. При выполнении визуализации вы можете использовать клавишу Пробел, чтобы развернуть любое из рабочих окон поверх остальных. Кроме того, такая разметка рабочей области предоставляет доступ к наиболее часто используемым окнам текстур и освещения.
Рис. 13.9. Выбор схемы рабочей области Hypershade/Render/Persp
Рис. 13.10. Окно Hypershade расположено вверху, Render View - слева внизу, a Perspective - справа внизу
Установки визуализации ading
Texturing
Render
Paint Effects
Help
Animation Editors Relationship Editors Sell I ngs i Prefe гея ces
Render Ciobals...
Attribute Editor... Dutiiner... Hypergraph...
Rendering Bags... Shadinfl Croup Attributes.
Hardwart Квпйег Buffer,..
Paint EfftttJ... UV Texture Editor.,,
Multilist*!-...
PlaybiaM... View ArrangeiienI Saved Layouts Sav« Current Layain. Fcame Selection in АЙ Views
OF
Console Window... liaise Main Window Ralie Application Windows
Рис. 13.11. Выберите нужное окно в меню Window ^ Rendering Editors
333
Можно настроить рабочую область и другим образом, например, открывать редак торы Hypershade или Render View по мере необходимости в отдельном окне. Выбери те нужное окно в меню Window ^> Ren dering Editors (Окно ^> Редакторы визуа лизации) - рис. 13.11. При этом указан ный редактор откроется в отдельном окне (рис. 13.12). Поскольку Attribute Editor (Редактор атрибутов) предоставляет доступ к большинству атрибутов источников света, допускается временно заменить окно Chan nel Box (оно расположено в правой части окна Maya) на окно Attribute Editor (рис. 13.13). Перейдите в восточную часть меню Hotbox и выберите пункты At tributes => Attribute Editor (Атрибуты "=> Редактор атрибутов) или щелкните пч кнопке j| в верхнем правом углу окна Maya. Окно Render View содержит множество инструментов, предназначенных для проведения качественной визуализации. Они рассматриваются в следующих разделах данной главы (более подробно окни Render View обсуждается в главе 15).
Рис. 13.12. Редактор Render View открыт в отдельном окне
Рис. 13.13. Окно Attribute Editor располагается в правой части рабочей области, заменяя окно Channel Box
334 Создание освещения
Источники света В Maya существует шесть типов источников света: подсветка^ протяженный, направленный, точечный, прожектор и объемный. Комбинирование этих источников позволяет добиться практически любого эффекта освещения. В сцене Maya используется один источник света или несколько в зависимости от настроения и художественного содержания сцены, Давайте рассмотрим различные типы и наиболее распространенные способы применения источников света: • Ambient (Подсветка). Создает общее однородное освещение для всей сцены. Для данного источника не рекомендуется устанавливать большое значение интенсивности, поскольку в этом случае сцена будет выглядеть плоской и лишенной контраста (рис. 13.14). Используется при создании освещения в комнате, в которой нет других источников света, а также освещения, не имеющего выраженного источника; • Area (Протяженный). Плоский двумерный элемент с регулируемыми размерами, который излучает свет от всей области в направлении линии, перпендикулярной его плоскости (рис. 13.15). Используется при создании ламп дневного света и прямоугольных световых бликов на стенах; •
Directional (Направленный). Свет распространяется извне под определенным углом. Эффект создается одновременно для всех объектов сцены вне зависимости от их расположения (рис. 13.16}. Применяется при имитации удаленных источников света, например солнца или луны;
Ambient Light Рис. 13.14. Пиктограмма подсветки
Area Light Рис. 13.15. Пиктограмма протяженного источника светг
Directional Light Рис. 13.16. Пиктограмма направленного источника света
Point Light Рис. 13.17. Пиктограмма точечного источника света
Источники света |"335]
Spotlight Рис. 13.18. Пиктограмма прожекторного источника света
Volume Light Рис. 13.18. Пиктограмма объемного источника света
• Point (Точечный). Распространяет свет от центра во всех направлениях. Чем дальше от источника света расположен объект, тем меньше он освещен (см. рис. 13.17). Используется при имитации света электрической лампочки:, свечи, факела; • Spot (Прожектор). Освещает сцену л у чом света в форме конуса. Свет идет от центральной точки, перемещается в определенном направлении и создает мягкие, плавные тени по краям (рис. 13.18). Применяется при имитации света настольных ламп, фонарей, фар автомобиля или прожекторов; •
Рис. 13.20. Общие атрибуты источников света; тип, цвет, интенсивность и коэффициент затухания
Volume (Объемный). Является разновидностью источника Spot. Отличие состоит в том, что форму светового потока задает пользователь ''рис. 13.19). Используется при имитации очень яркого света или пыльной среды.
Все источники света имеют следующие общие атрибуты (рис. 13.20): • Туре (Тип) определяет тип источника освещения, В любой момент можно изменить этот атрибут, например, вместо точечного источника света выбрать прожекторный; • Color (Цвет) задает основной цвет источника освещения. Допускается дополнить цвет картой изображений (image map,s); •
Рис. 13.21. Верхняя сцена освещена источником света низкой интенсивности. В нижней сцене использован тот же источник, но с более высокой интенсивностью
Intensity (Интенсивность) определяет яркость источника освещения. Чтобы получить лучшие результаты, начните с небольшой интенсивности света и постепенно увеличивайте ее (рис. 13.21);
336 Создание освещения Decay Rate {Коэффициент затухания) устанавливает снижение интенсивности света по мере удаления от источника. При уменьшении коэффициента затухания резко возрастает интенсивность, поэтому необходимо увеличить/ уменьшить интенсивность света, чтобы добиться желаемого результата. Этот атрибут не используется в подсветке, направленном и объемном источниках света. Существует пять возможных значения этого параметра {рис. 13.22):
Направление света
- No Decay (Нет затухания). Свет имеет одинаковую интенсивность независимо от расстояния; - Linear Decay (Линейное затухание). Интенсивность света уменьшается прямо пропорционально расстоянию; - Quadratic Decay (Квадратичное затухание). Убывание интенсивности пропорционально квадрату расстояния от источника света. Интенсивность снижается медленнее, чем при Cubic Decay, но быстрее, чем при Linear Decay. Эта установка ближе всего к естественному затуханию света в природе; - Cubic Decay (Кубическое затухание). Интенсивность света снижается пропорционально кубу расстояния от источника, то есть ослабевает быстрее, чем при использовании Linear Decay и Quadratic Decay.
Рис. 13.22. Коэффициенты затухания, сверху вниз: каркасный вид сцены, нет затухания, линейное, квадратичное и кубическое
Источники света
337
Подсветка
Рис. 13.23. Создайте на сцене пять или шесть примитивов и расположите их в произвольном порядке
Подсветка представляет собой источник света, который присутствует на сцене нос ле выключения всех источников света. Он помогает различать контуры предметом в темноте, когда в комнате нет видимых источников света. Подсветка - самый простой тип источников освещения, поэтому его просчет не требует больших временных затрат. Это позволяет предва рительно оценить внешний вид сцены после визуализации всех объектов, не создавая других источников освещения.. Однако не рекомендуется использовать окружающий свет высокой интенсивное ти, так как он может сделать сцену визу ально плоской. Давайте создадим сцену для тренировки,
Создание новой сцены 1. Для создания новой сцены выберите пункты меню File New Scene (Файл =i* Создать сцену).
Рис. 13.24. Плоскость стала больше, чем другие объекты сцены
2. Создайте на сцене пять или шесть при митивов и расположите их в произвольном порядке так, чтобы каждый объект находился на сетке (рис. 13.23), 3. Выберите в меню Create пункты NURBS Primitive ^> Plane (Примитив NURBS =* Плоскость), чтобы создать плоскость. 4. Установите для плоскости такое значе ние масштаба, чтобы она была боль ше, чем другие объекты (рис. 13.24). 5. Сохраните сцену в файле с названием practice.mb.
22 э-81
338 Создание освещения Создание подсветки 1. Откройте файл practice.mb.
Display
Window
Ar
NURBS Primitives Polygon Primitives
2. Выберите пункты меню Create => Lights (Создать => Источники света), затем в подменю щелкните по значку рядом с пунктом Ambient Light (рис. 13.25). 3. В открывшемся диалоговом окне Create Ambient light Options (Настройки создания подсветки) щелкните по образцу цвета рядом с атрибутом Color (рис. 13.26). Откроется окно выбора цвета. 4. Щелкните по полю выбора цвета, чтобы выбрать цвет источника освещения (рис. 13.27).
Subdiv Primitives
^m
Volume Primitives Ambient Light
Cameras
Directional Light
CV Curve Tod
Point Light
EP Curve Tool Pencil Curve Tool
Spot Light
Arc Tools
Volume Light
Area Light
Рис. 13.25. Щелкните по значку рядом с пунктом меню Ambient Light
5. Щелкните по кнопке Apply (Применить), чтобы изменить цвет подсветки. 6. Нажмите кнопку Create, чтобы создать подсветку. В сцену practice.mb добавляется источник света Ambient. 7. В контекстном меню верхней части Hotbox выберите разметку Hypershade/Render/Persp, чтобы разделить экран на три рабочих окна.
Рис. 13.26. Щелкните по образцу цвета рядом с атрибутом Color
8. Выберите в окне Render View пункты меню Render ^> Render => persp (Визуализация => Визуализация ^> Перспектива), чтобы визуализировать сцену в окне перспективы (рис. 13.28). Не используйте в сцене более одного источника подсветки, если в этом нет необходимости. Подсветка может превратить трехмерную сцену в визуально плоскую.
Рис. 13.27. Выберите цвет в поле, напоминающем радужный шестиугольник iPK
Орс от
REDO hcviaiK Render Rtnder Region
О is pi ay
Рдги!
• | II
Рис. 13.28. Чтобы визуализировать сцену, выберите в окнз Render View пункты меню Render ^> Render Attribute Editor или нажав клавиши Ctrl+a. 2. Присвойте атрибуту Ambient Shade значение 0 (рис. 13.31). Свет будет ранномерно распределен по всей сцене.
Рис. 13.30. Атрибуту Ambient Shade присвоена значение 1, при этом достигается эффект точечного освещения Ambient Shade
Рис. 13.31. Присвойте атрибуту Ambient Shade значение О
3. Чтобы выполнить визуализацию окна Perspective, выберите в рабочем окне Render View пункты меню Render ^> Render persp. Поскольку значение атрибута Ambient Shade равно О, объекты на сиене будут сливаться друг с другом, создавая плоское изображение (рис. 13.29). 4. Не снимая выделения с источника света, перейдите в окно Attribute Editor и присвойте атрибуту Ambient Shade значение 0,7. Свет, распространяемый источником, будет подобен точечному свету, поскольку его интенсивность постепенно снижается по мере удаления от источника освещения.
340 Создание освещения 5. Щелкните по кнопке Redo Previous Render g (Повторить предыдущую визуализацию) в окне Render View. Так как значение атрибута Ambient Shade увеличилось, сцена приобрела необходимую глубину (рис. 13.30). 6. В окне Attribute Editor присвойте параметру Intensity (Интенсивность) значение 0,25 (рис. 13.32). Это позволяет снизить интенсивность подсветки и свести двумерный эффект к минимуму.
Рис. 13.32. Установите интенсивность света равной 0,25 File
Edit
View
Create
Create Lights Lights C. Ambient Liciht
7. Щелкните по кнопке Redo Previous Render в окне Render View. Сцена станет очень темной.
Area Light
Протяженный источник света идеально подходит для имитации источника освещения прямоугольной формы, например люминесцентных ламп. Он также применяется для создания задней подсветки персонажа. Следует отметить, что несколько протяженных источников света в сцене может увеличить время визуализации.
Point Light
Directional Light
Spot Light Volume Light
РИС. 13.33
Выберите пункт Area Light
Создание протяженного источника света 1. Откройте файл practice.mb. 2. В окне Hypershade перейдите на панель Create и выберите в разделе Create Lights пункт Area Light (рис. 13.33). 3. Измените масштаб источника света до нужных вам размеров. 4. Переместите источник света и поверните его таким образом, чтобы поверхность излучала свет на объект, который требуется осветить (рис. 13.34). 5. Выделите источник света и откройте окно Attribute Editor. 6. Щелкните по образцу цвета рядом с атрибутом Color. 7. В открывшемся окне выберите цвет источника освещения.
Рис. 13.34. Направьте источник света на объект, который требуется осветить
Источники света 341 8. Щелкните по кнопке Accept (Принять), чтобы применить цвет. 9. Чтобы задать яркость источника света, переместите ползунок атрибута Intensity в окне Attribute Editor. 10. Закройте окно Attribute Editor. 11. В контекстном меню верхней части Hotbox выберите разметку Hypershade/Render/Persp, чтобы разделить экран на три рабочих окна. Рис. 13.35. Чтобы выполнить визуализацию сцены, выберите в окне Render View пункты меню Render ^ Render => persp
12. В окне Render View выполните команды меню Render ^ Render ^> persp, чтобы визуализировать сцену в окне Perspective (рис. 13.35).
Направленный источник света Направленный источник освещения идеально подходит для имитации солнечного и лунного света,
Создание направленного источника света Рис. 13.36. Положение направленного источника света, которое задается по умолчанию
Рис. 13.37. Лучи света по умолчанию распределяются по горизонтали
1. Откройте файл practice.mb, 2. Выберите в меню Create п у н к т ы Lights ^> Directional Light (Свет На правленный источник света). По умолчанию созданный источник освещения повернут по оси Z в отрицательном направлении (рис. 13.36), а лучи света распределяются по горизонтали (рис. 13.37).
342
Создание освещения
3. Щелчком мыши выделите направленный источник света. Поворачивайте его вокруг осей, пока стрелки не будут показывать в том направлении, куда вы желаете направить свет (рис. 13.38). 4. Не снимая выделения с источника, укажите в окне Channel Box другое значение интенсивности света. 5. Выберите в меню Window пункты Rendering Editors "=> Render View (см. рис. 13.39}. Редактор Render View откроется в новом окне. 6. Выберите в окне Render View пункты меню Render => Render ^> persp, чтобы визуализировать сцену в окне Perspective. Перемещение направленного источника света не влияет на освещение сцены, но позволяет впоследствии найти или выделить его.
Точечный источник света Точечный источник света идеально подходит для имитации света ламп и факелов. Он также используется в тех случаях, когда требуется немного усилить освещение в темном углу, уменьшить освещенность какой-либо области (то есть сделать источник поглощающим свет) или сымитировать свет, отраженный от объекта.
Рис. 13.38. Стрелки должны показывать в том направлении, куда вы желаете направить свет Д Liohting/Shadmg[Texturing
Animation editors Relationship Editor Sett! ng$/l*ref«renee5 Attribute Edttor... Quittner... Hypergraph...
Render
Paint Effects
Help
Hardware Rsndsr Buffer,., Render G tot) a Is... Hype s hadeRe ndwmg Flags,., Shading Group Ann butts...
Paint Effects... UV Texture Editor... Play blast... View Arrangement Saved Layouts Save Current Layout. Frame All in All Views Frame Selection in Ml Views Console Window... Raise Main Window Rais* Application Windows
Рис. 13.39. Выберите пункты меню Rendering Editors c> Render View, чтобы открыть редактор Render View в новом окне
Источники света 343 Создание точечного источника света 1. Откройте файл practice.mb. 2. Выберите в выпадающем меню панели Create пункт Create Lights (рис. 13.40), Рис. 13.40
Выберите в выпадающем меню в окне Hypershade пункт Create Lights
3. Используя среднюю кнопку мыши, перетащите значок Point Light из панели Create Lights на панель Work Area в окне Hypershade (рис. 13.41). 4. Дважды щелкните по значку Point Light на панели Work Area, чтобы открыть окно Attribute Editor. 5. Присвойте значение атрибутам Color и Intensity и закройте окно Attribute Editor. 6. Щелчком мыши выделите источник света и поместите его над плоскостью, Следите за тем, чтобы плоскость не. заслоняла источник света (рис. 13.42), 7. В контекстном меню верхней части Hotbox выберите разметку Hypersha de/Render/Persp, чтобы разделить экран на три рабочих окна.
Рис. 13.41. Используя среднюю кнопку мыши, перетащите значок Point Light из панели Create Lights на панель Work Area в окне Hypershade
Рис. 13.42. Поместите источник света над плоскостью
8. В окне Render View выполните коман ды меню Render => Render ^> persp, чтобы визуализировать сцену в окш: Perspective (рис. 13.43).
Рис. 13.43. Финальная визуализация сцены
344 Создание освещения Если атрибут интенсивности имеет отрица-
тельное значение, источник света будет поглощать освещение из окружающей области. TGI-ILUna
•JUS
МГТПииМИ
ГЙОТЭ
ГЛ/ПйТ
ЯгИ%Пр 1 ¥ 4- £. 7* П^ | 1-4 !"•* Т » ™в- »— "
|| I
Рис. 13.44. Задайте маску Object Pick так, чтобы выбрать только источники света
Прожектор Прожектор используется при имитации света театральной рампы, фар, настольных ламп, карманного фонарика, то есть всех источников, лучи которых имеют коническую форму.
Создание прожектора 1. Откройте файл practice.mb. 2. Щелкните по значку Spotlight ff% в полке Rendering, чтобы создать прожектор. 3. Задайте маску Object Pick (Выбор объекта) таким образом, чтобы выбирать только источники света (рис. 13.44), и перетащите указатель через значок Spotlight на сцене. Если вы правильно установили Object Pick, то будет выделен только источник света.
Рис. 13.45. Чтобы поместить прожектор над землей, перетащите манипулятор перемещения по оси Y
4. Выберите инструмент Show Manipulator (Показать манипулятор), нажав клавишу t или щелкнув по кнопке ц| на панели инструментов. 5. Перетащите манипулятор перемещения по оси прожектора так, чтобы поместить его над плоскостью (рис. 13.45). Обратите внимание, что при работе с инструментом Show Manipulator цель прожектора связана со вторым манипулятором и свет направляется на нее. 6. Выберите центральный квадрат манипулятора цели и переместите его в то положение, куда требуется направить источник света {рис. 13.46). 7. В контекстном меню верхней части Hotbox выберите разметку Hypershade/Render/Persp, чтобы разделить экран на три рабочих окна.
Рис. 13.46. Переместите манипулятор цели в новое положение
Источники света 345 8. В окне Render View выполните команды меню Render => Render ^> persp, чтобы визуализировать сцену в окне Perspective (рис, 13.47).
Атрибуты прожектора Maya позволяет переопределять некото рые атрибуты прожектора. Ниже приво дится их описание:
Рис. 13.47. Выберите пункты меню Render => Render => persp, чтобы выполнить визуализацию сцены в окне Perspective
• Cone Angle {Угол конуса света). Чем большее значение присвоено этому ат рибуту, тем шире будет конус света и освещенная область - рис. 13.48; • Penumbra Angle (Угол полутени). При изменении угла полутени граница между светом и тенью становится ме нее резкой. Если этот атрибут имеет от рицательное значение, граница размы вается внутри конуса света, при поло жителыюм значении - размываются области за пределами светового конуса (рис. 13.49);
Рис. 13.48. Вверху показана освещенная область при значении Cone Angle, задаваемом по умолчанию. Внизу - освещенная область стала шире, хотя положение источника света осталось прежним
Рис. 13.49. При изменении угла полутени граница между светом и тенью становится менее резкой. В верхней части рисунка значение атрибута равно 0, в нижней-7
346 Создание освещения • Dropoff (Затухание). Изменяет интенсивность света от центра области освещения к ее границе. При увеличении значения этого атрибута интенсивность света меняется плавно от центра к границе (рис. 13.50). Maya позволяет добавлять растровое изображение или процедурную текстуру ко многим атрибутам источника света. В качестве примера рассмотрим использование изображения в атрибуте цвета. При этом происходит проецирование изображения через поле света, что напоминает эффект прохождения света через мозаичное окно. В результате на плоскости возникает световой узор (рис. 13.51).
Объемный источник света Объемный источник света используется для освещения нескольких объектов, расположенных на одинаковом расстоянии друг от друга. Он позволяет сразу осветить все предметы, попадающие в область его действия.
Рис. 13.50. Атрибут Dropoff определяет изменение интенсивности света от центра области освещения к ее границе. В верхней части рисунка значение равно 0, в нижней-8
Создание объемного источника света 1. Откройте файл practice.mb. 2. Выберите в меню Create п у н к т ы Lights => Volume Light (Свет ^> Объемный источник света) - рис. 13.52. 3. Масштабируйте сферу Volume Light до тех пор, пока она не будет окружать все объекты, которые требуется осветить (рис. 13.53). Рис. 13.51. Область, освещенная источником света, на который было наложено изображение
Источники света Window •
Awnate
Defcrm
Sfcetett
;ESPn-ii
Polygon Primitives
Delotmation
An
aubdv Primitives
4. Выберите в меню Window пункт Attribute Editor. Откроется окно Attribute Editor. 5. Задайте атрибуты Color и Intensity. затем закройте окно Attribute Editor (рис. 13.54).
Volume Primitives Ught!
СV Curve Tool
6. В контекстном меню верхней части Hotbox выберите разметку Hypershade/Render/Persp, чтобы разделить экран на три рабочих окна.
EP Cuive Tocr Pencil Curve Tool Arc Tools Measure Tools
Construction Plane
347
О
Locator Annotation., Empty Group Sets
7. В окне Render View выполните команды меню Render => Render => persp, чтобы визуализировать сцену в окне Perspective (рис. 13.55).
Рис. 13.52. Чтобы создать на сцене объемный источник света, выберите в меню Create пункты Lights ^ Volume Light
Рис. 13.54. Для получения нужной яркости и цвета освещения задайте атрибуты Color и Intensity IPR
Options Display
Pane
Redo Previous RendeRsrder Р.едюп
Рис. 13.53. Значок Volume Light похож на сферу. Объекты, которые требуется осветить, должны находиться внутри нее
Рис. 13.55. В выпадающем меню Render выберите вид, который требуется визуализировать
348 Создание освещения Добавление карты изображения к атрибуту Color 1. Щелчком мыши выделите прожектор. 2. Выберите пункты меню Window ^ Attribute Editor (рис. 13.56), 3. В окне Attribute Editor щелкните по значку f рядом с ползунком Color, чтобы открыть панель Create Render Node (Создать узел визуализации).
General Editors Rendering Editor* Animation Editors Relationship Editor* Settings/ Preference Quiiiiter... Hypergrapli...
Рис. 13.56. Выберите пункты меню Window Attribute Editor
4. На панели Create Render Node в разделе 2D Textures (Двумерные текстуры) выберите пункт File (рис. 13.57). 5. Щелкните в разделе File Attributes (Атрибуты файла) по значку File 2j рядом с атрибутом Image Name (Название изображения), 6. В диалоговом окне Open (Открыть) найдите папку, в которой содержится изображение, выберите его и нажмите кнопку Open. 7. В контекстном меню верхней части Hotbox выберите разметку Hypershade/Render/Persp, чтобы разделить экран на три рабочих окна. 8. Выберите в рабочем окне Render View пункты меню Render ^> Render ^ persp, чтобы выполнить визуализацию сцены в окне Perspective. Результат визуализации представлен на рис. 13.58.
Рис. 13.57. На панели Create Render Node перейдите на вкладку Textures, затем в разделе 20 Textures выберите пункт File
Рис. 13.58. Слева 'показано изображение, использованное а атрибуте цвета источника света, а справа - результат визуализации
Вид из источника света 349
Вид из источника света
Perspective Orthographic Loqk Through Selected Panel Layouts Saved Layouts Tear Off.. Tear Off Copy.., Panel Editor..,
Рис. 13.59. Выберите в меню рабочего окна или меню Holbox пункт Look Through Selected
Одной из нелегких задач, которые приходится решать новичку, является освещение нужной области сцены. Maya немного упрощает ее выполнение, позволяя смотреть на сцену из источника света. Вы можете экспериментировать до тех пор, пока источник света не будет направлен именно туда, куда вы желаете.
Просмотр сцены из источника света 1. Выделите источник света, который требуется направить на нужный объект. 2. Выберите в рабочем окне пункты меню Panels => Look Through Selected {Пане ли ^> Смотреть из выделенного) - см. рис. 13.59. Теперь вы увидите сцену с по зиции источника освещения (рис. 13.60), Чтобы нацелить источник света на объект, выделите объект и выберите пункты менк: View => Look at Selection (Смотреть => Смотреть на выделенный объект).
Рис. 13.60. В настоящий момент сфера центрирована относительно прожектора. Окружность вокруг объекта задает область освещения для прожектора
350 Создание освещения
Привязывание источника света Привязывание источника света позволяет наиболее гибко и результативно работать с освещением. Устанавливая подобную связь, вы можете указать, что поверхность должна освещаться только заданными источниками света или источник света должен освещать лишь определенные поверхности. В обоих случаях допускается изолировать от света какие-либо объекты и контролировать освещение остальных областей сцены. Рекомендуется использовать привязывание при освещении персонажа, если требуется акцентировать внимание зрителей, то есть осветить только персонаж, но не всю сцену. Кроме того, по мере усложнения сцены необходимо перейти к привязыванию источников лишь к тем объектам, которые действительно нуждаются в освещении, иначе время визуализации значительно возрастет.
Рис. 13.61. Создайте простую сцену для демонстрации привязывания источника света Те» ч» ng Render Pant E
i
Л Assign New Materia assign Existing Matena1
Mate Light Links Break Light Lrts
Привязывание источника света к объекту 1. Создайте новую сцену, включающую два прожектора и три примитива. Расположите их так, как показано на рис. 13.61. 2. Выберите в меню Lighting/Shading (Освещение/Тонирование) пункты Light Linking =£• Light-Centric (Привязывание источника света Привязывание по источнику) - рис. 13.62. Откроется окно Relationship Editor (Редактор отношений). 3. В левой части окна Relationship Editor выберите источник света, который требуется связать с объектами. 4. В правой части окна выберите объекты. При необходимости отмените выделение объектов, которые не нужно освещать (рис. 13.63).
Рис. 13.62. Чтобы привязать один источник света к нескольким объектам, выберите пункт меню Light-Centric Ч Relationship Editor
Light So List Edit Sho™
1st Eclt Sho
niirbsS pliers' pplanel +3
IM\ initials ladings roup
Рис. 13.63. Источник света Spotlightl будет освещать только объект NurbsCylinderl
Привязывание источника света 351 5. Повторите шаги 3 и 4 для каждого источника света, с которым требуется связать объекты.
Options Help ОЬ|вс1 Cerlnc Lighl Linking I Ijrnnaled Objects List Edit Show
LigMSourc Let Edt Show
6. Выполните визуализацию сцены, чтобы оценить результат,
nurbCjilnderl pPlansI jniMlPsticeSE
Рис. 13.64. Слева выберите объект NurbsSpherel: а справа - источники света, которые должны его освещать. В данном примере единственным источником освещения NurbsSpherel будет Spotlight?
Чтобы быстро выбрать объект, следует щелкнуть мышью и перетащить указатель в окне Relationship Editor по названиям объектов.
Привязывание объекта к источнику света 1. Создайте новую сцену, включающую два прожектора и три примитива. 2. Выберите в меню Lighting/Shading пункты Light Linking c> Object-Centric (Привязывание источника света ь> Привязывание по объекту). Откроется окно Relationship Editor. 3. В левой части окна Relationship Editor выберите освещаемый объект (рис. 13.64).
Рис. 13.65. В данной сцене источники света привязаны к определенным объектам, поэтому поверхность, на которой находятся объекты, не освещается
4. В правой части окна выберите источники света для освещения объекта, При необходимости отмените выделение источников света, которые не должны освещать объект. 5. Повторите таги 3 и 4 для каждого освещаемого объекта. 6. Выполните визуализацию сцены, чтобы оценить результат (рис. 13.65).
352
Создание освещения
Имитация теней Тени являются очень важной составляющей сцены, поскольку они зрительно привязывают объекты к поверхности, а также дают представление о том, на каком расстоянии находятся объекты друг- от друга (рис. 13.66). Сцену, в которой объекты не отбрасывают теней, трудно признать реалистичной. В реальной жизни цвет тени зависит от цвета источника освещения. Солнце имеет желтый цвет, поэтому тени, отбрасываемые предметами, которые освещены солнечным светом, окрашены в фиолетовый цвет. При создании теней следует помнить о том, что в природе нет абсолютно черного цвета, существуют только концентрации темных цветов. А вам, как настоящему художнику, в работе над трехмерными сценами предстоит подражать природе, чтобы добиться настоящего реализма. Присмотритесь к тому, как выглядят тени в вашей комнате. По мере удаления от предмета тень размывается и постепенно исчезает. Начинающие художники часто забывают об этом, и нарисованные ими тени выглядят слишком густыми и неестественными. Создавая тень, необходимо помнить, что самая темная ее часть находится на небольшом расстоянии от границы, разделяющей объект и его тень (рис. 13.67).
Создание теней По умолчанию источники света в программе Maya не создают теней, поскольку для расчета теней требуется значительное время. Вы должны самостоятельно указать источники, создающие их. Чтобы увидеть тени при визуализации, потребуется активировать их не только
Рис. 13.66. Тени позволяют зрительно привязывать объекты к поверхности
Рис. 13.67. Саман темная часть тени располагается на небольшом расстоянии от границы объекта, рядом с основанием тени
Имитация теней
353
для источников света, но и для объектов. Объект не будет отбрасывать тень, даже если включены тени для источников света, Это предоставляет пользователям Maya зна чительную свободу при работе с тенями.
Рис. 13.68. Тень на основе карт глубины
Рис. 13.69. Тень на основе трассировки лучей
В Maya существует два типа теней; теш на основе карт глубины (depth shadow map) - в дальнейшем глубинная тень (рис. 13.68) и тень на основе трассировки лучей - далее трассированная тень (см, рис. 13.69). Оба метода позволяют создавать реалистичные тени, однако при использовании трассировки лучей можно получить более естественную тень, затратив меньше усилий па ее создание. Одна ко визуализация трассированных теней занимает больше времени, поэтому выбор метода остается на ваше усмотрение, Здесь необходимо придерживаться золотой середины и получить максимально реалистичную тень, затратив минимум времени на ее визуализацию. Карты глубины позволяют получить достаточно реалистичную тень без больших затрат времени на визуализацию. На этапе визуализации программа создает карт) глубины, в которой содержится информация о том, насколько далеко расположены объекты от источников света и друг от дру га. Карта представляет собой файл изобра жения канала глубины, созданный при визуализации вида от источника света. На основе этой информации Maya определи ет, на какие поверхности падает свет, а какие остаются в тени. Иными словами, глубинная тень создана заранее и не требует повторных расчетов, а ее изображение накладывается на объекты сцены непосредственно перед визуализацией. Изображение заменяет реальную тень, экономя время, необходимое для расчета настоящей тени. При многократном использовании карт глубины запас сэкономленного вре мени становится весьма ощутимым.
23 э-81
354 Создание освещения Трассированные тени позволяют создать великолепные, реалистичные изображения, которые вы не сможете получить при использовании глубинных теней. Примером может послужить прозрачная тень, которую отбрасывает полупрозрачный объект (рис. 13.70). Однако трассированные тени имеют некоторые недостатки. Например, при визуализации с использованием IPR (интерактивного фотореалистичного визуализатора) они не отображаются (см. главу 15), и вы увидите их только в финальном визуализированном изображении. Это еще одно следствие невысокой скорости визуализации трассированных теней, поэтому визуализатор IPR следует применять только при работе с глубинными тенями. Глубинные тени, которые используются для любого источника света, кроме подсветки, выглядят достаточно реалистично, и при этом их визуализация не занимает много времени.
Создание глубинной тени
Рис. 13.70. Глубинная тень не позволяет передать прозрачность объекта (вверху), чего нельзя сказать о тени с трассировкой лучей (внизу) KJ Spot Light Attributes »j Light Ertecfef ^J Shadows »J Depth Mop Shallow Attributes 17 Use-Depth Map Shadows Dnmp Resolution ?96
1. Выделите источник света, от которого требуется создать тень. 2. Откройте окно Attribute Editor. 3. Щелкните по стрелке рядом с заголовком Shadows (Тени), чтобы открыть список опций для работы с тенями, 4. Отметьте флажок Use Depth Map Shadows (Использовать глубинные тени) под заголовком Depth Shadow Map Attributes (Атрибуты глубинной тени) - рис. 13.71.
r
j:::::::::
Г? Use Mid Dial Dfwp Г 7 USB Dmap Aulo Focus
Рис. 13.71. Отметьте флажок Use Depth Map Shadows
Имитация теней 355 Shadow color
Рис. 13.72. Щелкните по образцу цвета в поле Shadow Color, чтобы открыть окно Color Chooser ШШШШШЖШ
Selectedfocus
Attributes
6. В окне Color Chooser выберите нужный цвет щелчком мыши.
Неф
nurbsSpftemShepel I mnkeNLirbSpharel I infrali nurbs Surface. rurbsSphereS-iapel
-
У NURBS Surface HiBtory У NURBS Surface Display JJ TeseeHwion (J Texture Mop _M_ DispiacamentUep Render Stats Casts Shadows Receive Shadows Motion Btur F
|7 ^sfete in йвЯе li? VJEibfeinRefra F ОвиЫе Sided Г '"-I. .-:T
Select
Load Attributes
5. Чтобы открыть окно Color Chooser (Выбор цвета), в разделе Shadows (над разделом Depth Map Shadow Attributes) щелкните по образцу цвета в поле Shadow Color (Цвет тени) - рис. 13.72.
CopyTafe
Рис. 13.73. Отметьте флажок Casts Shadows в разделе Render Stats окна Attribute Editor
Рис. 13.74. Сцена с использованием глубинной тени после визуализации
7. Нажмите кнопку Accept, чтобы применить цвет. 8. Выделите поверхность, которая должна отбрасывать тени. 9. Убедитесь в том, что в разделе Render Stats (Параметры визуализации) редактора Attribute Editor для поверхности отмечен флажок Cast Shadows (Отбрасывать тени) - см. рис. 13.73. Он устанавливается по умолчанию. 10. В контекстном меню верхней части Hotbox выберите опцию Hypershade/ Render/Persp, чтобы разделить экран на три рабочих окна. 11. Выберите в окне Render View пункты меню Render => Render ^> persp, чтобы выполнить визуализацию сцены в окне Perspective. После визуализации вы увидите созданную вами глубинную тень (рис. 13.74).
356
Создание освещения
Атрибуты глубинной тени • Dmap Resolution (Разрешение карты глубины) определяет разрешение карты глубины. Если разрешение слишком низкое, на границах тени произойдет дискретизация (рис. 13.75). Рекомендуется выбрать минимально возможную установку для этого атрибута, которая позволяет получить приемлемое качество, поскольку увеличение его значения отрицательно скажется на скорости визуализации;
Рис. 13.75. Если эазрешение карты теней слишком низкое, на границах тени произойдет дискретизация
• Dmap Filter Size (Размер фильтра карты глубины) позволяет управлять размытостью или мягкостью границ тени (рис. 13.76). Чтобы сэкономить время, не присваивайте этому атрибуту значение, превышающее 3; • Dmap Bias (Смещение карты глубины) задает смещение тени относительно объекта, который ее отбрасывает. Обычно используется принимаемое по умолчанию значение этого атрибута за исключением следующих случаев; - если тень отделена от поверхности, вам следует постепенно уменьшить значение атрибута Dmap Bias, пока тень не будет выглядеть естественно; - если на освещенных поверхностях появляются темные пятна, необходимо постепенно увеличить значение атрибута Dmap Bias, пока пятна не исчезнут. Трассированные тени позволяют создавать очень реалистичные изображения, однако при их использовании скорость визуализации существенно падает.
Рис. 13.76. Атрибут Dmap Filter Size контролирует сглаженность границ тени
Имитация теней О Jit
Seleclea
Attribute Editor1 spotUghtShapel Copy
Г onus
Ami bales
357
Прежде чем приступить к созданию трассированных теней, вам следует проверить три условия: • в редакторе Attribute Editor для источника света должен быть отмечен флажок Use Raytraced Shadows (Использовать трассированные тени}; •
Рис. 13.77. В окне Attribute Editor для источника света установите флажок Use Ray Trace Shadows
в разделе Render Stats редактора Attribute Editor для каждого объекта, который будет отбрасывать тень, должна быть выбрана опция Cast Shadows;
• в разделе Raytracing Quality (Качество трассировки лучей) в окне Render Globals (Общие установки визуализации) следует отметить флажок Raytracing (Трассировка лучей) - см. главу 15.
Создание трассированной тени 1. Выделите источник света, от которого требуется получить тень, 2. В разделе Raytrace Shadow Attributes (Атрибуты трассированной тени) в окне Attribute Editor для источника света установите флажок Use Ray Trace Shadows (Использовать трассированные тени) - рис. 13.77.
358
Создание освещения
3. В разделе Shadows (над разделом Raytraced Shadows Attributes) щелкните по образцу цвета в ноле Shadow Color, чтобы открыть окно Color Chooser,
Animation Editors Relationship Editors Setting s/Preferences
4. В окне Color Chooser щелчком мыши выберите нужный цвет.
Attribute Editor... Outliner... Hypergraph...
5. Нажмите кнопку Accept, чтобы применить цвет,
Paint Effects... UV Texture Editor,,.
6. Выделите поверхность, которая должна отбрасывать тени. 7. Установите флажок Cast Shadows в разделе Render Stats редактора Attribute Editor для поверхности. 8. Чтобы открыть панель Render Globals (рис. 13.78), выберите пункты меню Window 4* Rendering Editors => Render Globals (Windows), Window => Render Globals (Macintosh) или щелкните по кнопке Render Globals jjjjg в окне Render View. 9. В разделе Raytracing Quality на панели Render Globals отметьте флажок Raytracing (рис. 13.79). 10. На панели Render View выберите пункты меню Render ^> Render ^ persp, чтобы выполнить визуализацию сцены в окне Perspective.
ti n в / S ha d in в Jtxturin в
Render
Paint Effects
Help
Rendering Flags... Shading Group Attribute!...
Playblasi... View Arrangement Saved Layouts Save Current Layout... Frame All in All Views Frame Selection in All Views Console Window... Raise Mam Window Raise Application Win tows
Рис. 13.78. Чтобы открыть панель Render Globals выберите пункть меню Window "=> Rendering Editors «-> Rendei Globals
Render Gkjbab Pi*: / Ustfs/eaBny/Dotun s«i is. (ma* i! proierisi dtf auft / images/ FH*Namt' iifttitl«tjff
» Inug* Flh Output ^ Resolution »• Ami -il in sing QUiIHy Quality
[2
> Hindir Option! » M*mory and P«rforn«iif» Options >• lCRO(Hn
V Hinder Uy«r/P*ss >• F«nt Effects Rendering Opuoni
Рис. 13.79. На панели Render Globals отметьте флажок Raytracing
Имитация теней 359 Атрибуты трассированной тени • Light Radius (Радиус света) задает плавность границы тени, используя размер источника света. Например, меньший по размерам источник света создает более резкие тени, а больший - плавные1 тени (рис. 13.80); • Shadow Rays (Теневые лучи I определи ет величину зернистости, которая проявляется вдоль границ тени (рис. 13.81). При увеличении этого атрибута умень шается скорость визуализации, поэто му рекомендуется устанавливать минимальное значение, позволяющее сохранить качество изображения;
Рис. 13.80. Трассированная тень, которая задается по умолчанию (вверху), и тень с использованием атрибута Light Radius (внизу]
Рис. 13.81. Атрибут Shadow Rays определяет сглаженность тени
• Ray Depth Limit (Предел глубины луча) определяет, должен ли объект отбросить тень, если свет отражается от нескольких зеркальных поверхностей до попадания на объект.
ШИРОЩШ
н мшкш
14
Все объекты Maya при моделировании окрашены в серый цвет. Чтобы задать для объекта другой цвет или наложить текстурную карту (изображение, которое наносится на поверхность), следует создать для него тонировщик (shatter). Присмотритесь к окружающим вас предметам. Даже если все они будут окрашены в один и тот же цвет, вы всегда отличите мех от шелка или дерево от стекла. Maya позволяет создавать очень реалистичные модели при помощи самых разнообразных тонировщиков. Например, можно сделать поверхность хромированной (блестящей и отражающей) или выточенной из камня (с вмятинами и без бликов) рис. 14.1.
Рис. 14.1. Два объекта имеют одинаковую форму и цвет. Однако для них были созданы различные тонировщики, поэтому кажется, что предметы изготовлены из разных веществ
Тонировщики и материалы Блестящие и матовые поверхности неодинаково отражают свет. В Maya материал — это часть тонировщика, которая контролирует блеск и цвет объекта (в дополнение к ряду других атрибутов). Существует несколько типов материалов, и все они по-разному просчитывают отражение света. Одним из важных факторов, определяющих отражение света от поверхности, является зеркальный блик. Зеркальный блик представляет собой область поверхности, которая кажется самой яркой, так как отражает свет. При работе с зеркальным бликом вы можете добиться того, что объекты будут выглядеть выполненными из разных субстанций. Например, глазное яблоко имеет очень маленький и плотный зеркальный блик, а пластмассовая поверхность - широкий и расплывчатый (рис. 14.2). Включенная электрическая лампочка не блестит и не отражает свет, поэтому ее модель не будет реалистичной, если просто окрасить ее в желтый цвет. Однако при добавлении к тонировщику лампочки атрибута накаливания (incandescence) создастся впечатление, что она является источником света. Кроме того, можно окружить объект свечением (glow). Комбинирование накаливания и свечения позволяет создать очень удачную имитацию (рис. 14.3).
Рис. 14.2. Свет отражается по-разному в зависимости от того, какой тип материала использован для поверхности
Рис. 14.3. Для материала модели задано накаливание и свечение
361
362 Тонировщики и материалы
Управление текстурами и тонировщиками в редакторе Hypershade В окне Hypershade вы будете выполнять большую часть работы с тонировщиками. Здесь находятся материалы, текстуры, источники света и утилиты. Материал представляет собой узел, который включает большинство средств управления внешним видом поверхности. Набор средств зависит от использованного при создании модели материала (рис. 14.4). Текстура представляет собой изображение, которое чаще всего накладывается на цвет или рельеф объекта. При наложении на рельеф поверхность объекта будет неровной. Значения яркости (по черно-белой шкале) отдельных точек изображения определяют высоту рельефа. С помощью текстуры также можно определить, какие части поверхности должны быть блестящими или прозрачными, а также осветить отдельные области. В Maya существует две категории текстур: растровое изображение и процедурная текстура. В качестве растровой текстуры можно использовать простые изображения, например, отсканированную фотографию. Процедурная текстура также является изображением, однако рассчитывается с помощью математической формулы. Примером процедурной текстуры является фрактал (рис. 14.5). Осталось рассмотреть еще один тип узлов, доступных в окне Hypershade, - утилиты. Утилиты Maya по-разному влияют на тонировщики. В качестве примера обычных утилит можно привести утилиту bumb2d, которая позволяет создавать рельеф, и утилиту 2d placement, которая используется для размещения текстуры на поверхности.
Рис. 14.4. Это базовые материалы, доступные в окне Hypershade
Рис. 14.5. Сфера слева имеет фрактальную текстуру, сфера справа - растровую
Управление текстурами и тонировщиками в редакторе Hypershade 363
Использование Hypershade Окно Hypershade разделено на три области: панель Create, вкладки Hypershade и вкладки рабочей области (work area).
Рис. 14.6. Панель Create, располагающаяся в левой части окна Hypershade, позволяет создавать узлы различных типов s Taxlures UlWes Lights
Cameras
Рис. 14.7. Вкладки Hypershade предоставляют доступ к различным узлам, разделенным по категориям
Рис. 14.8. Рабочая область позволяет создавать связи между различными узлами. Здесь текстура ramp соединена с цветом материала Blinn
Откройте выпадающее меню панели Create и выберите из списка одну из следующих опций: Create Materials {Создать материалы), Create Textures (Создать текстуры), Create Lights (Создать источники света), Create Utilities (Создать утилиты) и Create All Nodes (Создать все типы узлов). Набор пиктограмм на панели Create изменяется в соответствии с тем, какой тип узла был выбран. Например, если вы щелкнули по пункту Create Lights, появятся пиктограммы для всех типов источников света (рис. 14.6). На вкладках Hypershade находятся все созданные вами материалы, текстуры, утилиты, источники света и камеры. Если вы использовали в сцене какой-то из этих узлов, он отобразится на соответствующей вкладке. Чтобы убедиться в этом, щелкните по материалу Blinn на панели Create, и он сразу же появится на вкладке Materials (рис. 14.7), Рабочая область позволяет создавать связи между материалами и текстурами. С помощью средней кнопки мыши пере местите нужные узлы из вкладок Hypershade в рабочую область, а затем при ступайте к созданию связи. Например, попробуйте связать текстуру с цветом ма териала. Удерживая нажатой среднюю кнопку мыши, перетащите текстуру на материал и выберите пункт Color или Default в появившемся контекстном меню, На рис. 14.8 изображена созданная связь,
364 Тонировщики и материалы Рассмотрим назначение кнопок, находящихся на панели инструментов окна Hypershade: •
л кнопка Toggle On/Off Create bar (Включить/выключить панель Create) позволяет скрыть или отобразить панель Create. Скрыв панель, вы получаете дополнительное пространство для работы с другими узлами;
•
^ кнопка Clear Graph (Очистить граф) очищает рабочую область (узлы при этом не удаляются);
•
^ кнопка Rearrange Graph (Перестроить граф} приводит к исходному виду рабочую область, которая постепенно заполняется по мере создания новых узлов;
• jg кнопка Graph Materials on Selected Objects (Отобразить материалы выделенных объектов) позволяет определить, с какими материалами связан конкретный объект. Выделите объект, затем щелкните по этой кнопке, и в рабочей области появятся все узлы, связанные с его материалом; •
& кнопка Show Up and Downstream Connections (Показать исходящие и входящие соединения) показывает список всех узлов, соединенных с выделенным узлом. Выделите материал и щелкните по этой кнопке, чтобы материал IT все связанные с ним узлы отобразились в рабочей области;
• ~ — -Я эти кнопки управляют видом окна Hypershade. Слева расположена кнопка Show Top Tabs Only (Показывать только верхние вкладки). В центре находится кнопка Show Bottom Tabs Only (Показывать только нижние вкладки). Справа расположена кнопка Show Top and Bottom Tabs (Показы вать верхние и нижние вкладки).
Понятие материалов 365
Понятие материалов
Рис. 14.9. Для каждой модели был задан различный тип материала {слева направо): Anisotrapic. Blinn Lambert, Phong и Phong E
Рис. 14.10. Окно Attribute Editor для материала Blinn. Параметры, задаваемые в этом окне, позволяют определить внешний вид поверхности
Maya предлагает несколько типов материалов, включая Lambert, Blinn, Phong, Layered, Ocean, Ramp и Anisotropic. Уни кальные свойства каждого материала позволяют различным образом отражать свет. Например, у материала Lambert нет зеркального блика, поэтому он кажется матовым, а материалы Blinn и Phong выглядят блестящими. Материал Anisotropic тоже блестит, но в отличие от материалов Blinn и Phong он отражает свет неодинаково в разных направлениях !рис. 14.9). Maya также включает два особых материала (Ramp и Layered), о которых будет рассказано далее. Материал Ocean, который воспроизводит динамику жидкостей, будет подробно рассмотрен в главе 16. Свойства материалов (каналы) в Maya можно разделить на следующие основные категории: цвет (color), прозрачность (tranparency), цвет подсветки (ambient color), накаливание (incandescence) и рель еф (bump). Допускается задавать изображения для любых каналов, и большинству из них может быть назначен цвет или определенная яркость (для управле ния каналом важен не цвет, а яркость тек стуры по черно-белой шкале). В редакто ре Attribute Editor (Редактор атрибутов; находятся все атрибуты соответствующе го материала (рис. 14.10).
Общие атрибуты материалов Рассмотрим атрибуты, находящиеся в спис ке Common Material Attributes (Общие свойства материалов), более подробно: • Color (Цвет) определяет цвет объек та. Можно выбрать цвет в окне Color Chooser или привязать изображение к цвету;
366 Тонировщики и материалы •
Transparency (Прозрачность) позволяет сделать поверхность частично прозрачной. С помощью ползунка можно увеличить или уменьшить прозрачность поверхности или привязать изображение к данному атрибуту, чтобы сделать прозрачной (или частично прозрачной) только часть поверхности. Для этого атрибута важна только яркость изображения. Белый цвет соответствует прозрачным участкам поверхности, а черный - непрозрачным (рис. 14.11};
• Ambient color (Подсветка) позволяет придать свечение основному цвету материала. Передвигая ползунок, можно ровно осветить всю поверхность или привязать изображение к подсветке, чтобы сделать ярче только определенные участки поверхности; • Incandescence (Накаливание) заставляет материал светиться. Как правило, объекты сцены видимы только в том случае, если освещены источником света. Однако если для материала объекта задан ненулевой параметр Incandescence, то объект будет визуализирован даже в том случае, если в сцене нет источников света; • Bump mapping (Наложение рельефа) определяет неровности поверхности. Чтобы увидеть воздействие данного атрибута, необходимо связать с ним изображение. Белые участки изображения соответствуют самым высоким неровностям, а темные — самым низким; однородное серое изображение не будет создавать рельеф (рис. 14.12).
Изменение цвета объекта 1. Выберите в меню Window пункты Rendering Editors ^ Hypershade.
Рис. 14.11. Узел в нижнем правом углу представляет собой текстуру, которая была привязана к плоскости как карта прозрачности. Участки изображения, окрашенные в белый цвет, стали прозрачными
Рис. 14.12. Узел в нижнем правом углу представляет собой текстуру, которая определяет рельеф плоскости. Белые области соответствуют высоким точкам, темные - низким. Чтобы увидеть результаты наложения рельефа, необходимо выполнить визуализацию сцены
Понятие материалов Lambert
Work Area Shoe
367
2. В выпадающем меню панели Create щелкните по пункту Create Materials (если он еще не выбран). 3. Нажмите кнопку Lambert (рис. 14.13). В рабочей области (нижней правой половине окна) появится новый материал.
Phong PhongE Shading Map
Рис. 14.13. Это часть окна Hypershade. При нажатии кнопки Lambert появляется новый узел материала под названием Iambert2
4. Дважды щелкните по новому материалу, чтобы открыть для него окно Attribute Editor (рис. 14.14). 5. Щелкните по значку ;»• рядом с полем Color, чтобы открыть окно Color Chooser (рис. 14.15). 6. Выберите цвет из основных цветов в верхней части окна или из шестиугольной палитры.
„ !
7. Щелкните по кнопке Accept, чтобы закрыть окно Color Chooser.
Malenei Sample
8. При помощи средней кнопки мыши перетащите материал из окна Hypershade на поверхность;
Type J Lambert jj Common Mnwfel Attributes
или Bump Mapping
- т
Рис. 14.14. Окно Attribute Editor для материала, созданного в редакторе Hypershade
Выделите поверхность, затем щелкните по материалу правой кнопкой мыши. Выберите в появившемся контекстном меню пункт Assign Material to Selection (Назначить материал выделенному объекту) - рис. 14.16.
Salad Qb|eds Wilti Material am Frame Objects With Malaria
Рис. 14.15. Выберите цвет из основных цветов в верхней части окна или из шестиугольной палитры
Attribute Editor Rename Help on "lembert"
Рис. 14.16. Щелчком правой кнопки мыши вызовите контекстное меню и назначьте материал выделенной поверхности. Контекстное меню также рекомендуется использовать при одновременном применении тонировщика к нескольким поверхностям
368 Тонировщики и материалы Если вы собираетесь назначить поверхности тонировщик и перетаскиваете его из окна Hypershade, убедитесь, что вы выполняете перемещение в тонированном режиме. Если установлен каркасный режим, вам придется с максимальной точностью поместить тонировщик на изопарм или ребро поверхности, что достаточно трудно сделать.
Текстурирование поверхностей NURBS Поверхность NURBS всегда имеет четыре стороны. Сфера не является исключением - она ограничена сторонами сверху и снизу, а две другие стороны сходятся на меридиане. Кроме того, поверхности NURBS характеризуются направлениями U и V. При работе в плоскости значения координаты по направлению U увеличивается слева направо, а по направлению V - снизу вверх. Это значит, что нижний левый угол является начальной точкой (рис. 14.17). Любое изображение, используемое в качестве текстуры, также является четырехсторонним, поскольку файлы изображения имеют форму квадрата или прямоугольника. Левый нижний угол изображения помещается в начальную точку поверхности. Нижняя часть изображения привязывается к поверхности в направлении U, а левая часть - в направлении V (рис. 14.18). После размещения изображения па поверхности допускается перемещать, вращать и повторять его. Если требуется поместить одно изображение на несколько поверхностей, следует использовать проецирование. При этом изображение как бы проецируется на поверхность из проектора слайдов. Б Maya есть готовые наборы текстур, но можно использовать и другие изображения
Рис. 14.17. На этсй плоскости отображены контрольные точки, которые позволяют определить направление U и V. Квадрат в левом нижнем углу является начальной точкой, координата по направлению U возрастает вправо от нее, а по направлению V- вверх. Это значит, что ось U направлена слева направо, а V - снизу вверх
Рис. 14.18. Одно и то же изображение привязано к разным поверхностям NURBS. Изображение оборачивается вокруг поверхности, а его ориентация зависит от направления осей U и V
Понятие материалов 369 j C /AW/ShaiterLJbn _| Building
(2_J RenderadSampli
в формате JPEG, TIFF и IFF (формат изображений Maya).
Назначение изображения из библиотеки Shader Library объекту NURBS 1. Выполните команды меню Create "=S> NURBS Primitive с» Plane (Создать ^ Примитив NURBS "=> Плоскость).
Рис. 14.1Э. Текстуры библиотеки Shader Library можно многократно повторять, закрашивая всю поверхность, и между ними не будет переходов, то есть образуется сплошной узор
2. В меню Panel любого рабочего окна выберите пункты меню Panel => Panel => Ну pershade (Панель ^ Панель ^ Окно Ну pershade). 3. Щелкните по кнопке Lambert на панели Create окна Hypershade, чтобы создать, новый материал. Материал Lambert по явится в окне Hypershade. 4. Назначьте материал плоскости, перета щив его с помощью средней кнопки мыши на поверхность. 5. Перейдите на вкладку Shader Library (Библиотека тонировщиков) в нижней части окна Hypershade.
Рис. 14.20. Когда вы связываете текстуру и материал, появляется контекстное меню, в котором вы можете выбрать, с каким атрибутом материала должна быть связана текстура
6. Щелкните по папке Textures в нижней части окна Hypershade. Справа появит ся несколько текстур (рис. 14.19). 7. С помощью средней кнопки мыши пе ретащите текстуру, имитирующую кир пичную кладку, на новый материал Lambert (он называется Iambert2), ко торый находится в верхней части окна Hypershade. 8. Выберите в открывшемся контекстном меню пункт Color (Цвет) - рис. 14.20, В узле Lambert появится текстура, имитирующая кирпичную кладку. Текстура будет связана с цветом материала Lam bert.
Рис. 14.21. На поверхности появилась текстура, имитирующая кирпичную кладку. Она видна только в режиме показа текстур 24э-81
9. Щелкните в окне вида Perspective, за тем нажмите клавишу б, чтобы перей ти в режим показа текстур. Текстура, имитирующая кирпичную кладку, отображается на поверхности (рис. 14.21).
370
Тонировщики и материалы
Создание карты изображений для объекта NURBS 1. Выполните команды Create "=> NURBS Primitive ^> Plane. 2. Откройте окно Hypershade. 3. Щелкните по кнопке Lambert, чтобы создать новый материал. Новый материал появится в окне Hypershade. 4. Дважды щелкните по материалу Lambert, чтобы открыть окно Attribute Editor. 5. Щелкните по значку Map (Карта) й% который находится справа от ползунка Color (рис. 14.22). Откроется окно Create Render Node (Создать узел визуализации). 6. Убедитесь в том, что в разделе 2D Textures выбран пункт Normal, затем нажмите кнопку File (Файл) в окне Create Render Node (рис. 14.23). Откроется окно Attribute Editor для узла файла.
Рис. 14.22. Щелкните по значку Map, чтобы назначить растровое изображение каналу цвета jy Creole Render Njide Ooiions
Help
Moieireis Textures j [jgh S Wft New Texture Placement
7. Щелкните по кнопке просмотра ^ рядом с полем Image Name (Название изображения). 8. Откройте файл с изображением. 9. С помощью средней кнопки мыши перетащите созданный материал Lambert из окна Hypershade на н у ж н у ю поверхность.
Рис. 1423. Выберите в окне Create Render Node текстуру, которую требуется привязать к атрибуту материала
10. Щелкните в окне вида Perspective, затем нажмите клавишу 6, чтобы перейти в режим отображения текстур. Теперь выбранное вами изображение привязано к каналу цвета поверхности (рис. 14.24). Аналогичным образом растровое изображение можно назначить любому атрибуту материала. Рис. 14.24. Изображение привязано к каналу цвета поверхности
Понятие материалов 37l] Чтобы назначить изображение, перетащите текстуру на название атрибута в окне Attribute Editor (рис. 14.25). Изображение, применяемое в качестве текстуры для поверхности NURBS, может быть расположено не так, как вы это задумали. Чтобы повернуть его, переместить или масштабировать, воспользуйтесь узлом place2dTexture Рис. 14.25. При помощи средней кнопки мыши перетащите текстуру из окна Hypershade на канал цвета материала в окне Attribute Editor
Использование узла place2dTexture 1. Привяжите текстуру с изображением кирпичной кладки к плоскости NURBS, как описывалось ранее в разделе «Назначение изображения из библиотек)! Shader Library объекту NURBS». 2. Выделите поверхность.
Рис. 14.26. В рабочей области окна Hypershade отображаются все узлы, которые связаны с данным материалом
3. Щелкните по кнопке Graph Materials on Selected Objects (Показать материалы выделенных объектов) $g в окне Hypershade. В рабочей области окна Hypershade отобразятся все соединения тонировщика (рис. 14.26). 4. Дважды щелкните по узлу place2dTexture в левой части рабочей области, чтобы открыть для него окно Attribute Editor. 5. Нажмите кнопку Interactive Placement (Интерактивное размещение) в окне Attribute Editor для узла p!ace2dTexture. На поверхности отобразится красная квадратная рамка с точкой в центре.
Рис. 14.27. Инструмент интерактивного размещения позволяет изменить положение текстуры на поверхности
6. Щелкните по центральной точке и, удерживая нажатой среднюю кнопку мыши, перетащите рамку по поверхности. Текстура переместится в этом же направлении (рис. 14.27).
372 Тонировщики и материалы 7. Перетаскивая рамку за углы при помощи средней кнопки мыши, вы заставите текстуру вращаться (рис. 14.28). 8. В окне Attribute Editor введите значение 4 в первое поле Repeat UV (Повторить по осям U и V) и нажмите клавишу Enter. Текстура кирпича повторится четыре раза в направлении U. Значение первого поля определяет повторение рисунка по оси U, а второго - по оси V. 9. Укажите во втором поле Repeat UV значение 4 и нажмите клавишу Enter. Теперь текстура будет повторяться четыре раза в направлении V (рис. 14.29). Процедурные текстуры рассчитываются математическими алгоритмами, в отличие от карты изображения, которая создается на основе растровой картинки. Наиболее часто в сценах Maya используется текстура Ramp, которая похожа на обычный градиент.
Назначение поверхности текстуры Ramp 1. Выполните команды Create с> NURBS Primitive ^> Sphere. 2. Перейдите в окно Channel Box, введите значение 90 в поле Rotate X (Повернуть по оси X) и нажмите клавишу Enter. 3. Щелкните по кнопке Phong E на панели Create окна Hypershade. Материал Phong E появится в рабочей области. 4. В окне Hypershade дважды щелкните по материалу Phong E, чтобы открыть цля него окно Attribute Editor, 5. В окне Attribute Editor нажмите кнопку Map yr рядом с ползунком Color. Откроется окно Create Render Node.
Рис. 14.28. Перетаскивая рамку за углы, вы заставите текстуру вращаться
17 Угар U Repeal UV 1-1 000 |l DO О Offset [(ПК)О
JO COO
Relate UV |0000
Рис. 14.29. Параметр Repeat UV узла place2dTexture определяет повторение текстуры на поверхности
Понятие материалов 373 в в Create Render Node f Materials f*TWfi»ti*'f Lights f т •
With New Texture Placement iy2D Textures |5 Normal 0 As projection © As stencil Bulge
Checker
Cloth
File
11
Fractal
Grid
\-
Mountain
Movie
\\. If'
Ramp |\ \i
•,",[',•! Clow
Рис. 14.30. Щелкните по кнопке Ramp в окне Create Render Node, чтобы создать и привязать к материалу новую текстуру Ramp
6. Щелкните по кнопке Ramp (рис. 14.30), чтобы открыть окно Attribute Editor для текстуры Ramp. Узел текстуры появится в окне Hypershade. 7. При помощи средней кнопки мыши перетащите материал Phong E из окна Hypershade на сферу, чтобы назначить ей тони'ровщик. Если материал Phong E не виден в окне, щелкните по рабочей области окна Hypershade и нажмите клавишу а. Все узлы будут показаны в рабочей области, 8. Щелкните в окне вида Perspective, затем нажмите клавишу 6, чтобы оценить результат (рис. 14.31).
Создание модели глаза на основе текстуры Ramp 1. Создайте материал с текстурой Ramp и назначьте его сфере, как было описано в предыдущем разделе. 2. Дважды щелкните по текстуре Ramp в окне Hypershade, чтобы открыть для нее окно Attribute Editor. 3. В выпадающем списке Туре окна Attribute Editor измените тип текстуры на U Ramp,
Рис. 14.31. Атрибут цвета этой сферы соединен с текстурой Ramp
374 Тонировщики и материалы 4. Щелкните по круглому индикатору верхнего положения цвета и немного сдвиньте его вниз (рис. 14.32). 5. Переместите ползунок Selected Color (Выделенный цвет) налево до конца, чтобы изменить выбранный цвет на черный. 6. Щелкните по индикатору среднего положения цвета (по умолчанию он попадает на зеленый цвет спектра) и переместите его вплотную к индикатору верхнего положения цвета. 7. Щелкните в верхней части градиента, как показано на рис. 14.33. Появится новый индикатор положения цвета. 8. Сдвигайте вверх индикатор нижнего положения цвета, пока он не достигнет созданного вами индикатора. 9. Не снимая выделения с индикатора нижнего положения цвета, щелкните по образцу цвета рядом с ползунком Selected Color.
Рис. 14.32. Индикаторы положения цвета в окне Attribute Editor позволяют управлять внешним видом градиента, задаваемого текстурой Ramp. Они определяют положение цвета внутри градиента
Рис. 14.33. Создайте новый индикатор положения цвета. Его можно удалить, щелкнув по перечеркнутому квадратику в правой части градиента
Понятие материалов 375 10. Щелкните по образцу белого цвета в верхней части окна Color Chooser (рис. 14.34}. Сфера превратится в гла.ч (рис. 14.35).
Рис. 14.34. В окне Color Chooser выбран образец белого цвета. Поэтому выделенный индикатор положения цвета и градиент в нижней части приобрели белый цвет
Помимо двумерной текстуры Ramp в но вой версии Maya имеется одноименный то нировщик. Тонировщик материала Ramp (как и текстура Ramp) используется для создания более сложных текстур, включая рисованное тонирование поверхностей, которое позволяет получить двумерный эффект, а также более тонкие градиентные переходы. Новый тонировщик Ramp так же может имитировать текстуру глаза, который был создан в предыдущем разделе.
Создание простого эффекта рисованной поверхности 1. Выберите в меню Create пункты NURBS Primitive ^> Sphere.
Рис. 14.35. К глазу были добавлены зрачок и радужная оболочка
2. В выпадающем меню Create Materials щелкните по кнопке Ramp Shader (Тонировщик Ramp), чтобы создать тони ровщик Ramp (рис. 14.36). 3. В окне Hypershade дважды щелкните по материалу Ramp Shader, чтобы от крыть для него окно Attribute Editor. 4. Щелкните по образцу цвета Selected Color, чтобы открыть окно Color Chooser. Selected Position J0.164 Selected Cobr
РИС. 14.36
В выпадающем меню Create Materials выберите тонироещик Ramp Shatter
шЭ
Interpolafen I Linear
^j
Cobr Input
Light Angle
^
Рис. 14.37. Щелчок по градиенту Color добавляет новый цвет
376 Тонировщики и материалы 5. Выберите цвет для теневой области сферы.
Color SetectedPosfon |0.164
6. Нажмите кнопку Accept, чтобы закрыть окно Color Chooser. 7. Щелкните по градиенту Color над ползунком Selected Color. К ползунку будет добавлен новый цвет (рис. 14.37). 8. Щелкните по образцу цвета Selected Color и присвойте параметру Value (V) значение 1 в окне Color Chooser. 9. Нажмите кнопку Accept, чтобы закрыть окно Color Chooser. 10. В выпадающем списке Interpolation (Интерполяция) выберите значение None (Нет). Установка None изменяет градиент с двумя цветами на два однородных цвета без градиента (рис. 14.38).
Рис. 14.38. Текстура Ramp будет оставаться градиентом до тех пор, пока вы не присвоите параметру Interpolation значение None Selected Position [ci.QOO ннНШМЩ
Selected Color II Interpolation
• «" Чопе
_у_|
Рис. 14.39. Чтобы задать для ползунка Color только два цвета, без градиентов, присвойте параметру Interpolation значение None
11. В поле Color Input (Ввод цвета) установите значение Brightness (Яркость). Это позволит сделать сферу визуально плоской и придать ей «мультяшный» вид. 12. Создайте два цвета на градиенте справа от поля Selected Color в разделе Incandescence. Сделайте левый цвет белым, а правый-черным (рис. 14.39). 13. Присвойте параметру Incandescence Interpolation значение None, 14. После назначения материала создается впечатление, что сфера нарисована на белой бумаге, а затем вырезана (см. рис. 14.40). При создании градиентов рекомендуется использовать различные оттенки одного цвета. Это позволяет подчеркнуть форму объекта, поскольку человеческий глаз воспринимает оттенки одного цвета как составляющие одной поверхности, а несколько цветов зрительно разбивают поверхность.
Рис. 14.40. Визуализация в «мультяшном» стиле
Понятие материалов
377
Создание многослойного тонировщика
r Node Орин Help
1. Выполните команды Create ^ NURBS Primitive => Sphere.
Materials ГенИ*« j |_ghts j UHH* i* Vitl- ЧичТюГшеЙасёлий
2. Создайте два материала Blinn. Задайте цля одного красный цвет, а для другого - синий. 3. Дважды щелкните по синему материа лу Blinn в окне Hypershade. 4. Нажмите кнопку Map 1-е. рядом с ползунком Transparency (Прозрачность). Рис. 14.41. К каналу Transparency добавьте фрактальное изображение, чтобы видеть красный тонировщик сквозь синий •w Cieate Materials •rj Surface AnJsdicpc Binn Lambert Layaed Shader Ocean Shadei Phong
; Рис. 14.42. Для \ создания многослойного тонировщика щелкните по кнопке Layered Shatier или ! с помощью средней | кнопки мыши перетащите значок в окно Hypershade
Рис. 14.43. С помощью мыши можно перетаскивать обычные тонировщики на многослойные и таким образом создавать многослойные эффекты, используя прозрачность каждого слоя
5. Щелкните по кнопке Fractal (Фрактал) на вкладке Textures окна Create Render Node (рис. 14.41). 6. Нажмите кнопку Layered Shader (Мне гослойный тонировщик) и выпадающем меню Create Materials окна Hypershade (рис. 14.42), 7. В окне Hypershade дважды щелкните по материалу Layered Shader, чтобы открыть для него окно Attribute Editor, 8. При помощи средней кнопки мыши перетащите красный и синий материалы из окна Hypershade в красную рамку раздела Layered Shader Attributes (Атрибуты многослойного тонировщика) - рис. 14.43,
378 Тонировщики и материалы 9. Щелкните по перечеркнутому значку под первым зеленым квадратом, чтобы удалить квадрат (рис. 14.44). В красной рамке Layered Shader Attributes остались два квадрата. 10. Примените многослойный тонировщик к сфере. 11. Выберите в меню Window пункты Rendering Editors c> Render View.
•v Layered Shade i Allribulei
P
•
Рис. 14.44. Перечеркнутый значок под каждым квадратом используется для удаления простых тонировщиков из состава многослойного
12. Щелкните по кнопке Redo Previous Render el- (Повторить предыдущую визуаi L I , i лизацию) в окне Render View. Сфера приобрела красный и синий цвета, при этом красный цвет просвечивает сквозь синий, поскольку фрактальное изображение было добавлено к каналу прозрачности (рис. 14.45). Чтобы отобразить нижний тонировщик, задайте прозрачность для всех верхних тонировщиков.
Назначение карты рельефа 1. Выполните команды Create => NURBS Primitives => Plane. 2. Создайте материал Lambert в окне Hypershade. 3. Назначьте материал Lambert плоскости, перетащив значок материала из окна Hypershade на плоскость с помощью средней кнопки мыши. 4. В окне Hypershade дважды щелкните по материалу Lambert, чтобы открыть для него окно Attribute Editor. 5. Нажмите кнопку Map Щ рядом с полем Bump Mapping (Наложение рельефа). Откроется окно Create Render Node. 6. Щелкните по кнопке Bulge (Выпуклость) - рис. 14.46. В рабочей области окна Hypershade появится узел текстуры Bulge. Чтобы увидеть рельеф, эту текстуру необходимо визуализировать.
Рис. 14.45. Многослойный тонировщик при визуализации приобрел красно-синюю расцветку
Help TexWrasLicjhlE Р with h|fflwTexJure "JgQ Texture в Directional Light (Источники света => Направленный источник света). Рельеф лучше отображается при использовании направленного источника света, чем при подсветке. 8. Поверните источник света таким образом, чтобы он был направлен на плоскость по диагонали (рис. 14.47). Рис. 14.47. Лучи света падают на плоскость по диагонали. Направленный источник света подчеркивает рельеф, поскольку свет поступает только с одной стороны
9. Щелкните по кнопке Render (Визуализировать) ..£§., которая находится в верхнем правом углу главного окна или на соответствующей полке. Изображение будет визуализировано в новом окне, Поверхность приобретает рельефность (рис. 14.48).
Регулировка высоты рельефа 1. Создайте рельефную плоскость, как было описано в предыдущем разделе, 2. Выделите плоскость. Рис. 14.48. Текстура выпуклости привязана к каналу рельефа плоскости. Чтобы отобразить рельеф, необходимо выполнить визуализацию •а е- ст Cieole Materials -I Surface
Рис. 14.49. Все узлы, связанные с материалом, отображаются в рабочей области окна Hypershade Утилита, регулирующая высоту рельефа, расположена в середине
3. Щелкните по кнопке Graph Materials on Selected Objects в окне Hypershade. Материал и все его соединения появятся в рабочей области окна Hypershade (рис. 14.49). 4. Дважды щелкните по узлу bump2d, чтобы открыть для него окно Attribute Editor.
380 Тонировщики и материалы 5. Уменьшите высоту рельефа, перетащив ползунок или указав новое значение (рис. 14.50), 6. Щелкните по кнопке Render тт. У§. Рельеф стал менее глубоким, чем был при предыдущей визуализации (рис. 14.51).
Проекционные текстуры Проекционная текстура позволяет наложить одно изображение на несколько поверхностей. По умолчанию задан плапарный тип проекции. Примером проекций такого типа может послужить проецирование изображения на экран в кинотеатре. Другие типы проекций - сферическая и цилиндрическая - проецируют изображение из формы, которая окружает поверхность (рис. 14.52).
Щ1 AtttibuluEdilur bumpZdl List
Selected
FP :tis
Attributes
Help
bump?d! Ibulge! 1 bumpZd: but
Li-
Uti I iV Sample
TJ Zd Bump Attributes Bump Veiue Bump Depth |0.5[iO Select
LoailAUrihutes
Рис. 14.50. В окне Attribute Editor измените значение атрибута Bump Depth, контролирующего общую высоту рельефа
Рис. 14.51. Слева атрибуту Bump Depth присвоено значение 1, а справа-0,5
Рис. 14.52. Текстура была привязана к сфере при помощи трех равных типов проекции: цилиндрической, планарной и сферической
Понятие материалов
381
Привязка текстуры в качестве проекции 1. Создайте в окне Hypershade материал Lambert, затем назначьте его плоскости NURBS и сфере NURBS (рис. 14.53). 2. В окне Hypershade дважды щелкните по материалу Lambert, чтобы открыть для него окно Attribute Editor.
Рис. 14.53. Сфера и плоскость NURBS е
V CreatR Mender Node
_Не1р Materials Textos jughis | i. У With NewTaxtgrp Placement »J2Q Textures 4~ Norm^ As prajerlibn
3. Щелкните' по кнопке Map /* рядом с ползунком Color в окне Attribute Editor. Откроется окно Create Render Node. 4. Выберите переключатель As projection (Как проекция) - рис. 14.54. 5. Щелкните по кнопке File. Откроется окно Attribute Editor для проекции. В окне Perspective появится узел place3dTexture. 6. Перейдите на вкладку fllel в верхней части окна Attribute Editor, чтобы отобразить настройки файла текстуры. 7. Щелкните по значку папки рядом с надписью Image Name. Откроется окно для выбора файлов.
Рис. 14.54. В окне Create Render Node был выбран переключатель As projection
8. Найдите и откройте файл с нужным изображением. 9. Откройте окно Perspective и нажмите клавишу 6, чтобы перейти в режим отображения текстур. Маркер утилиты place3dTexture появится в окне Perspec tive. Изображение проецируется сбоку, поэтому оно вытянуто вдоль плоскости (рис. 14.55).
Рис. 14.55. Планерная проекция вытягивает изображение вдоль плоскости
Если вы переместите поверхность, к которой была привязана проекционная текстура, то при визуализации будет казаться, что поверхность движется сквозь текстуру Для решения этой проблемы выделите по верхность, затем выберите в меню Texturing (Текстурирование) пункт Create Texture Reference Object (Создать объект ссыл ки на структуру).
382 Тонировщики и материалы Изменение проекции 1. Свяжите проекционную тексгуру с плоскостью, как было описано в предыдущем разделе. 2. Выделите утилиту place3dTexture в окне Perspective (рис. 14.56). Линия, выходящая из центра, показывает направление проекции. В данном случае изображение проецируется сбоку, а требуется направить проекцию на верхнюю часть плоскости. 3. Поверните плоскость на -90° относительно оси X. Изображение не вытягивается, однако оно не совсем совпадает
Рис. 14.56. Выдепите утилиту placeSdTexture в окне Perspective, чтобы перемещать, вращать и масштабировать этот узел, как и любой другой объект
С ПЛОСКОСТЬЮ.
4. Не снимая выделения с утилиты place3dTexture, нажмите клавиши Ctrl+a, чтобы открыть окно Attribute Editor для данного узла. 5. Щелкните по кнопке Fit to group box (Подогнать по размерам группы). Размеры утилиты place3dTexture будут автоматически подогнаны под размеры плоскости (рис. 14.57).
П
При перемещении или вращении утилиты place3dTexture изображение на поверхности также будет перемещаться или вращаться. Изменение размеров утилиты приведет к уменьшению/увеличению изображения (рис. 14.58).
Рис. 14.57. Размеры утилиты placeSdTexture подогнаны под размеры плоскости, поэтому изображение проецируется через обе поверхности
Рис. 14.58. Утилиту placeSdTexture уменьшили, повернули и переместили
Понятие материалов
383
Текстурам, особенно проецированным, часто недостает резкости, даже если они четко визуализируются. Чтобы правильно поместить текстуру, требуется видеть изображение более отчетливо.
Повышение качества изображения текстуры в окне вида Рис. 14.59. Текстура была спроецирована на сферу. Она кажется очень размытой, поэтому трудно представить, как объект будет выглядеть после визуализации
4. В окне Hypershade дважды щелкните по материалу, чтобы открыть для него окно Attribute Editor.
Material Sample >Г Noda Behavior |
Hardwoie
Texturing
_
Textuisd channel 1 Colo' »I • _ ___ — -• Тейыгэ qualUy | Delimit ^1 Seta»
2. Выделите сферу. 3. Щелкните по значку Graph Materials on Selected Objects ^ в окне Hypersha de, чтобы отобразить материал и все его соединения в рабочей области.
У Attiiliule hdilor lambertZ
ч"
1. Спроецируйте текстуру на сферу (см. рис. 14.59). Текстура на поверхности кажется очень размытой.
i
' ----- — ---I i-pod Attributes I CopyTab
Рис. 14.БО. Откройте раздел Hardware Texturing окна Attribute Editor и присвойте параметру Texture quality значение High, чтобы отчетливо отобразить текстуру
Рис. 14.61. После изменения параметров в разделе Hardware Texturing текстура сферы стала более четкой
5. Щелкните по стрелке под заголовком Hardware Texturing в окне Attribute Editor, чтобы раскрыть список дополнительных настроек (рис. 14.60). 6. Присвойте параметру Texture quality (Качество текстуры) значение High (Высокое). Текстура сферы станет отчетливой {рис. 14.61). При улучшении качества текстуры скорость прорисовки Maya снизится, особенно при работе с изображением высокого разрешения. Завершив размещение текстуры, измените ее качество на более низкое.
384 Тонировщики и материалы
Инструмент 3D Paint
г
Инструмент 3D Paint (Трехмерное рисование) позволяет рисовать на поверхности. При помощи этого метода можно получить новую картинку для текстуры, a Maya затем создаст файл изображения. Перед началом рисования важно убедиться в том, что папка проекта задана верно (выберите пункты меню File "=> Project ^ Set), так как текущим проектом определяется, где должно сохраниться изображение. При сохранении файла в папке 3dPaintTextures рабочего проекта будет создана папка с названием сцены, в которую будут помещаться ваши рисунки. Допускается рисовать на поверхности, на которой уже размещена текстура с изображением, чтобы добавлять реалистичные подробности, например грязь или другие детали,
JO MID
J"
jrj Cnta
Flood Paint
|
FbodEiaaa f Settled
Flood " A H
Рис. 14.62. Настройки, располагающиеся в окне 3D Paint Tool Settings, определяют внешний вид мазков кисти File Texluie* Ailrbute to Pan; I Cdor Image Fwnwt | Maya IFF [ff]
J*
Рисование на поверхности объекта
Assign/Ertt Т entires
1. Создайте в окне Hypershade материал Lambert и назначьте его сфере NURBS.
Retoad Fte Tenures
Save Т sutures
2. Выделите сферу. 3. В меню Texturing щелкните по значку рядом с пунктом 3D Paint, чтобы открыть окно 3D Paint Tool Settings (Установки инструмента 3D Paint) рис. 14.62. 4. Чтобы перейти к разделу File Textures (Файлы текстур}, воспользуйтесь полосой прокрутки - рис. 14.63. При необходимости укажите формат создаваемого изображения.
j
Г Update on Stroke Г" SeveTextuieonStioke !•? Extend Seam Color
Рис. 14.63. Задайте текстуру для материала выделенного обыжта в разделе File Textures окна 3D Paint Tool Settings. Нельзя рисовать на поверхности, к каналу цвета которой не был привязан файл
Понятие материалов 385
BizeX J256
J 1
J
15 KeepAspeel Ratio Assign /EdHeidurBs
Close
Рис. 14.64, Щелкните по кнопке Assign/Edit Textures, чтобы связать текстуру файла с материалом объекта
5. Щелкните по кнопке Assign Textures (Назначить текстуры), чтобы открыть окно Assign File Textures (Назначить файлы текстур). В этом окне можно увеличить разрешение текстуры. По умолчанию устанавливается разрешение 256x256, которое пока не рекомендуется менять (рис. 14.64). 6. Щелкните по кнопке Assign Textures. Файл текстуры связан с материалом, поэтому можно начать рисование. 7. Перейдите в окно Perspective, удерживая нажатой клавишу Ь, и с помощью средней кнопки мыши перетащите указатель справа налево, чтобы отрегулировать размер кисти. Красная окружность, соответствующая размеру кисти, уменьшится.
Рис. 14.65. Проведите кистью по поверхности объекта. На сфере появился черный след
8. Щелкните по поверхности и перетащи те указатель мыши, чтобы начать рисовать. На поверхности появится след (рис. 14.65).
Использование инструмента 3D Paint Rood Paint Flood Выделить оболочку) - рис. 14.79. Все UV-точки в оболочке будут выделены.
Рис. 14.78. Редактор UV Texture Editor наглядно показывает, как различные части поверхности накладываются на карту изображения. UV-точка, которую вы выделили в окне Perspective, выделена и здесь. На ней располагаются манипуляторы перемещения. Это позволяет быстро отыскать оболочку, представляющую собой наушник телефона
Convert Selection to Faces Convert Selection Ic Edges UmvtM,S*l Select Camera (Вид "=> Выделить камеру) - рис. 15.14. Название выделенной камеры (persp) появилось в верхней части окна Channel Box. 3. Нажмите клавишу s, чтобы добавить камеру в ключевой кадр. 4. На ползунке Time измените текущее время, щелкнув по номеру 30. 5. Выполните откат, смещение и поворот камеры, чтобы изменить точку просмотра (см. главу 2). 6. Нажмите клавишу s, чтобы повторно добавить камеру в ключевой кадр. 7. Перейдите к началу анимации и воспроизведите ее с помощью кнопок управления на шкале времени (рис. 15.15), Так как движение камеры анимировано, при воспроизведении анимации вид из окна просмотра будет изменяться (рис. 15.16).
Рис. 15.12. В нижней части рабочего окна вы видите названии камеры, из которой производится съемка, в данном случае камеры persp. Обратите внимание, что при этом выделена другая камера
Channels Object camera 1 Translate XMJ7_ Translate Y ; 2 955 Transhte Z .' ?43 Rotate X;-30 624 Relate Vl-56.656_ Rotate z!o~' • Scale xrj.373__ SeaieY0.373_ Stale 1-0.373" Visibility on
Рис. 15.13. В окне Channel Box отображается название выбранной камеры. По умолчанию новой камере присваивается название camera 1
Sheeting Lighting Show
Next View Default Ho me Look at Selecto/ Frnroe All Frame Selection Predefined Bookmarks Bookmarks Gamera Saltings
Image Plane
Рис. 15.14. В окне Perspective выберите пункты меню View => Select Camera
Камеры 403 10. Выделите камеру, затем выберите в меню Panels окна Perspective пункты Panels c> Look Through Selected. Те перь вы видите сцену из анимировзнной камеры. При воспроизведении анимации сцена поворачивается таким образом, что объект виден с разных сторон,
Рис. 15.21. Создана кривая NURBS, которая проходит между несколькими конусами
Чтобы переместить центр трансформаций точно в начало координат, удерживайте нажатой клавишу х. Центр трансформаций будет привязан к сетке.
Анимация камеры вдоль пути 1. Создайте несколько конусов и расположите их в ряд. 2. В окне вида сверху создайте кривую NURBS, которая проходит между конусами (рис. 15.21). 3. Выберите в меню Create пункты Cameras с=> Camera. В окне Perspective появится новая камера, Рис. 15.22. Камера присоединена к пути движения, поэтому она переходит к началу кривой. Однако камера неверно направлена
4. Не снимая выделения с камеры, выделите кривую, удерживая при этом нажатой клавишу Shift. 5. Выберите в меню Animate (Анимировать) пункты Motion Paths =* Attach to Motion Paths (Пути движения О Присоединить к пути движения). Камера перейдет к началу пути (рис. 15.22). Теперь необходимо направить камеру. 6. Не снимая выделения с камеры, щелкните по пункту motionPathl в окне Channel Box, чтобы отобразить атрибуты пути движения.
406 Камеры и визуализация 5. Откройте файл с изображением. Затем закройте окно Attribute Editor. Выбранная вами картинка появится на плоскости изображения (рис. 15.28). Чтобы выделить плоскость изображения, необходимо задать маску выбора как Select by Component Type (Выбирать по типу компонента) г и щелкнуть по кнопке Miscellaneous (Разное) j?,. Чтобы переместить плоскость изображения, необходимо выделить ее и изменить параметры Center X, Y и Z в окне Channel Box. Плоскость легко удалить нажатием клавиши Delete. Чтобы скрыть плоскость изображения, снимите флажок Cameras в меню Show рабочего окна. Так как плоскость изображения является компонентом камеры, а камеру вы скрыли, плоскость изображения так* же будет скрыта.
Визуализация Визуализация выполняет вывод изображений после того, как вы завершите моделирование, анимацию, освещение и текстурирование сцены. Настройки визуализации находятся в окне Render Globals. Перед тем как приступить к конечному этапу создания сцены, вы должны решить, какого размера будет изображение после визуализации. Разрешение изображения - это его размер в пикселях. Выбор разрешения определяется средой, в которой будет использоваться изображение.
Рис. 15.28. На фони сцены появляется изображение восхода солнца. Картинка сохранит свое положение относительно камеры, даже если вы выполните откат, смещение или поворот
Визуализация 407 Для изображений, размещаемых на Webсайте, рекомендуется использовать разрешение 320x240 (задается по умолчанию!, поскольку высокое разрешение значительно увеличивает размер файла. Для видео в формате NTSC лучше выбрать разрешение 720x486 (рис. 15.29).
Рис. 15.29. Одна и та же сцена визуализирована с разным разрешением
Рис. 15.30. Сравните окончательное (production) качество (слева) и качество предварительного просмотра (preview) - справа. Изображение справа визуализируется намного быстрее, но выглядит хуже
Для печати необходимо использовать гораздо более высокое разрешение. Печать с разрешением 300 dpi обеспечивает полиграфическое качество изображения. Если требуется распечатать изображение размером 8 на 10 дюймов, следует выбрать разрешение 2400x3300. Визуализация изображения с таким разрешением займет очен ь много времени. Разрешение можно переопределить в окне Render Globals. Не менее значительную роль играет качество выходного изображения, определяющееся степенью сглаживания (antialiasing]. Изображения с низким качеством будут визуализироваться быстрее, поэтому их удобно использовать для тестирования, Установка высокого качества позволяет получить четкое изображение с плавными линиями и формами. Однако время визуализации существенно увеличится, поэтому задавать высокое значение данного параметра рекомендуется только для получения конечного результата (рис. 15.30). Перед визуализацией необходимо сохранить сцену и задать проект. Это позволяет избежать потери изображения, поскольку все визуализированные изображения будут автоматически отправляться в нужную папку.
410 Камеры и визуализация Установка общих атрибутов визуализации последовательности изображений 1. Задайте в окне Render Globals параметры камеры, укажите уровень сглаживания, разрешение и формат изображения, как было описано в предыдущем разделе. 2. Чтобы визуализированные изображения и файл сцены имели разные имена, измените названия файлов. Когда вы введете новое имя, названые файла R верхней части окна соответствующим образом изменится (рис. 15.36). 3. Выберите пункт name.#.ext в выпадаю щем списке Frame/Animation Ext. Изменение названия сразу же отобразится на экране. Чтобы визуализировать анимацию {то есть последовательность сменяющих друг друга изображений), а не одно изображение, следует выбрать опцию, которая включает символ «#». Опция name.#.ext используется при работе в среде Windows, однако для Macintosh или Irix лучше выбрать опцию name.* или name.ext.#, поскольку в этих системах применяются разные обозначения для имен файлов. Несколько вариантов имен, предлагаемых Maya, позволяют добиться максимальной гибкости при визуализации. Например, при установке name.# файлы будут называться по образцу happy.l, happy.2, happy.3. а при назначении name.ext.* happy.tif. 1, happy.tif. 2 и happy.tif.3. 4. Задайте начальный и конечный кадры анимации, чтобы визуализировать именно этот временной диапазон:
: D:/aniirew/mBya/prDJectE/bQok/imai;|e«/ File Name: billyTheRnhnt H1
J
Class
Рис. 15.36. В верхней части окна Render Globals появится новое название файла
Визуализация Path: D/andrew/maya/projects/boak/images/ File Name: billy! heRobiJt.Onni.tit To biHyTheRobatOOlUJtif
Рис. 15.37. В верхней части окна Render Globals отображаются имя файла и полный путь к нему
411
5. Присвойте параметру Frame Padding (Заполнение кадров) значение 4 и зак ройте окно Render Globals. Это позво лит дополнительно включить в название файла четыре цифры, чтобы впоследствии было удобно сортиро вать изображения по имени файл;| (рис. 15.37). 6. Укажите соответствующие параметры для выбранной технологии визуализа ции.
Рис. 15.38. Трассировка лучей позволяет сделать сцену более реалистичной
Если в качестве формата изображения вы выбрали AVI, Maya будет визуализировать единый файл фильма, а не последовательность отдельных нумерованных изображений.
Визуализатор Software Renderer Maya включает две базовые категории программной визуализации: установку по умолчанию, известную как А-буфер, или испускание лучей (raycasting), и трассировку лучей (raytracing). А-буфер позволяет создавать высококачественные изображения с освещением, тенями, текстурами и движением. Однако для достижения настоящего реализма изображений необходимо использовать отражения и преломления света (см. раздел «Трассировка лучей»). Чтобы изображение объекта невозможно было отличить от его реального прототипа, потребуется применить трассировку лучей (рис. 15.38).
414 Камеры и визуализация
Буфер аппаратной визуализации Программная визуализация занимает много времени. Чтобы оценить результат, не выполняя программной визуализации, воспользуйтесь аппаратной визуализацией. Аппаратная визуализация - это нечто среднее между предварительным просмотром анимации (playblast) и программной визуализацией. В результате вы получите группу экранных снимков сцены, По сравнению с предварительным просмотром аппаратная визуализация имеет ряд преимуществ. Она позволяет сгладить грани поверхностей и визуализировать размытие движения. Кроме того, при ее выполнении создается альфа-канал для более удобного комбинирования с другими изображениями (рис. 15.44). Вы можете ускорить рендеринг следующим образом: произведите аппаратную визуализацию для некоторых элементов сцены, а затем скомбинируйте финальные изображения с фоном, полученным с использованием программной визуализации. Однако программная визуализация позволяет достичь гораздо лучших результатов, чем аппаратная. Аппаратная визуализация не создает тени, отражения или преломления лучей и не так хороша для работы с текстурами и освещением. Многие эффекты, например, свечение, не отображаются, и вы не видите карты рельефа. Аппаратную визуализацию рекомендуется использовать при работе со сценами с минимальным количеством текстур или частиц, чтобы затем включить полученное изображение в качестве слоя в файл анимации с высоким разрешением (рис. 15.45).
Рис. 15.44. На рисунке представлен результат аппаратной визуализации объекта при активации опции Motion Blur и альфа-канал созданный для данного изображения
Рис. 15.45. Это изображение получено при помощи программной визуализации. Обратите внимание на карты рельефа, эффекты свечения и отражения света
Визуализация 41 б] Использование буфера аппаратной визуализации 1. Откройте или создайте сцену с анимацией. 2. Выполните команды меню Window ^> Rendering Editors Hardware Render Buffer, чтобы открыть окно Hardware Render Buffer. II
20 !
40 I
GO I
80 I
1I1D I
120 I
1411 I
Рис. 15.46. В меню Cameras выберите нужный вид mAttfibule Editor. defnultHarrtwarBRendrvCilniials
MX
4. Б окне Hardware Render Buffer выберите пункты меню Render с> Attributes (Атрибуты). Откроется окно Attribute Editor для визуализатора Hardware Render Buffer (рис. 15.47}. Вкладка HardwareRenderGlobals содержит габор настроек для вывода файлов изображения с использованием буфера аппаратной визуализации. Обратите внимание, что открывается другое окно, а не окно Render Globals, в котором устанавливаются атрибуты Hardware Renderer (Аппаратный визуализатор).
|_rj Image Output Files (ilEiiemg
Alpha Sours JCH Г Write ZDepih •j Render Modes Dra* ^s |in:icth"?ih&ded *] P Texlunng Г Упе Smoothing Г" f a9 Image c£sotmon Г 3eo.i)BtyMe£k Г .- , И MuHi-Pess Render Options
Рис. 15.47. Ha вкладке Hardware Render Globals можно задать название файла, разрешение, диапазон кадров и другие параметры буфера аппаратной визуализации
3. Выберите в меню Cameras (Камер >0 окна Hardware Render Buffer камеру, вид которой требуется визуализировать (рис. 15.46). Чтобы изменить вид просмотра, используйте откат, смещение и поворот камеры в окне Hardware Render Buffer.
I
5. Укажите название файла, расширение, начальный и конечный кадры, формат изображения и разрешение. 6. В окне Hardware Render Buffer выберите пункты меню Render ч> Render Sequence (Визуализация ^ Визуализация последовательности), чтобы выполнить быструю визуализацию последовательности кадров. Файлы изображений будут помещены в папку Images рабочего проекта.
416 Камеры и визуализация Настройка качества визуализации 1. Выберите в меню Window пункты Rendering Editors => Hardware Render Buffer. Откроется окно Hardware Render Buffer. 2. Определите параметры аппаратной визуализации, как было описано в предыдущем разделе. 3. Воспользуйтесь полосой прокрутки, чтобы перейти к разделу Multi Pass Render Options (Опции для многопроходной визуализации). Установите флажки Multi Pass Rendering {Много проходная визуализация) и Anti Alias Polygons (Сгладить полигоны) - см. рис. 15.48. 4. Щелкните по кнопке Test Render (Тестовая визуализация) в окне Hardware Render Buffer Щ, чтобы оценить результат. Программа создаст и скомбинирует три прохода изображения, сгладив все грани поверхностей. 5. Присвойте параметру Render Passes (Проходы визуализации} значение 5, а параметру Motion Blur (Размытие при движении) - значение 1. 6. Щелкните по кнопке Test Render в окне Hardware Render Buffer, чтобы оценить результат. 7. Программа выполнит пять проходов изображения. При значении параметра Motion Blur, равном 1, повторы выполняются со сдвигом в один кадр (рис. 15.49).
. " Attribute Editor detaullHariiwnicRunderfilobals
: pro
•>
Multi-pass Render Options
Fj RenderpessBs )3
"'
;
R.
Edge Smooth ing Motion Blur {i Display Optiuits Node Elehavior _>j Extra Attributes Sefed
I Lo
CopyTsir
Рис. 15.48. Установите флажки Multi Pass Rendering и Anti Alias Polygons, чтобы сгладить грани поверхностей
Визуализация 41 j]
Трассировка лучей
О
2fl t
4i 1
60 i
iO I
180 I
120
Рис. 15.49. Функция Motion Blur позволяет получить размытие при движении объекта
Рис. 15.50. Эта сцена создана исключительно из сфер, которые отражаются друг от друга
Рис. 15.51. Каждая прозрачная сфера имеет различный коэффициент преломления: слева 1,0, в центре -1,333, справа ~ 2,0
273-81
Расчет и прослеживание траектории лучей [трассировка) позволяют обеспечивать эффект преломления лучей света и отбрасывания теней прозрачными объектами, Единственный недостаток трассировки большие временные затраты и pecypcoeiviкость. Maya сначала направит лучи от камеры, чтобы определить, какие объекты видимы в текущем кадре, затем рассчитает лучи от источников света, чтобы найти элементы, которые окажутся освещенными. И наконец, рассчитает лучи от поверхностей элементов, для которых коэффициент отражения не равен нулю, чтобы установить, какие именно элементы будут отражаться. Чтобы создать эффект отражения, необходимо поместить в сцену несколько объектов и использовать алгоритм Raytracing (Трассировка лучей) - рис. 15.50. Преломление возникает при движении света сквозь оптически плотный, прозрачный материал, например, стекло или жидкость. Без данного эффекта стекло не выглядит реалистичным. Maya позволяет задать показатель преломления, определяющий степень искажения света при прохождении сквозь поверхность (рис. 15,31). Можно приводить самые разные примеры эффекта преломления. Наверное, на отдыхе возле реки или моря вы не раз пробовали поймать плывущую рыбу руками и всегда промахивались. Дело в том, что преломление искажает изображение рыбы, и при этом вам кажется, что она находится в другом месте, чем на самом деле. Чтобы схватить рыбу, вы должны сделать поправку на преломление света.
418 Камеры и визуализация Создание отражений 1. Создайте сцену с большой плоскостью, сферой, множеством кубов и несколькими источниками света (рис. 15.52), 2. Назначьте кубам материал Phong красного цвета, плоскости - материал Phong в клетку, а сфере - материал Phong с отражением. 3. Щелкните по кнопке Render Globals |g в окне Render View или выберите в меню Options пункт Render Globals. Откроется окно Render Globals. 4. Выберите в выпадающем списке Render Using пункт Maya Software и при свойте параметру Anti- Aliasing Quality Preset значение Production Quality. 5. Воспользуйтесь полосой прокрутки, чтобы перейти к разделу Raytracing Quality {Качество трассировки лучей), и откройте список параметров. 6. Установите флажок Raytracing, чтобы активировать алгоритм Raytracing (см. рис. 15.53). 7. Отобразите сферу полностью в окне Perspective, выделив ее и нажав клавишу f. Щелкните по кнопке Render gfij, чтобы открыть окно Render View и визуализировать сцену вместе с отражениями (рис. 15.54).
Рис. 15.52. Создайте сцену с плоскостью, сферой, окруженной множеством кубов, направленным и протяженным источниками света
Edti
Prssei
k/i ranges/
Path: O:/ond revr/moy a/p ra File Nome: unlilled ift
J*j Haytoedng QmaJity P| RslEeOiaiiS p Retraokjns|
'l
- |:
.*•
-
.
Рис. 15.53. В окне Bender Globals установите флажок Raytracing, иначе не будет выполняться визуализация отражений и преломлений
Maya позволяет управлять видимостью объектов в отражениях. Чтобы изменить статус объекта, выделите его и откройте окно Attribute Editor. Перейдите в раздел Render Stats (Параметры визуализации) и снимите флажок Visible in Reflections (Виден в отражениях).
Рис. 15.54. При выполнении визуализации сцены вы увидите отражения кубов в сфере
Визуализация Q Q Li ч Selected
419
Создание преломления
Attribute Editor Cnp; Fetus
1. Откройте сцену, созданную в предыдущем упражнении. Выделите сферу. 2. В окне Hypershade щелкните по кнопке Graph Materials on Selected Items (Показать материалы выделенных объектов) Cube (Полигоны =£ Куб). 3. Масштабируйте куб таким образом, чтобы его размеры позволяли имитировать лодку.
30 Э 81
466
Динамика
4. Не снимая выделения с куба, выберите пункты меню Fluid Effects ^> Ocean Make Boats (рис. 16,69). Куб наследован локатору. Локатор контролируется океаном и, в свою очередь, управляет движением куба (рис. 16.70),
Create 3D Container Create 20 Container AditfEdt Contents Create 30 Container л«Ь EntttM Create 20 Contwer «Mi [ratter Get ttiltl Exam*..
5. Выделите локатор и откройте окно Attribute Editor, нажав клавиши Ctrl+a. 6. В окне Attribute Editor перейдите на вкладку Extra Attributes. 7. Щелкните по кнопке Play на панели управления воспроизведением. 8. В интерактивном режиме измените такие атрибуты, как Buoyancy (Плавучесть), Water Damping (Испарение воды), Air Damping (Испарение воздуха), Roll (Поперечная качка) и Pitch (Продольная качка), чтобы определить движение лодки. Временной диапазон должен составлять не менее 500 кадров, чтобы было достаточно времени для воспроизведения эффекта. Итак, вы создали лодку и освоили использование атрибутов. Теперь перейдите к следующему упражнению - попробуйте создать катер. Выполните действия, описанные в предыдущем разделе, но на шаге 2 выберите пункты меню Fluid Effects Create Pond
Select
|
la»ifc^« I
СсруТЛ
j
Ров
Рис. 16.72. Измените цвет в атрибутах Pond
1. Выберите в меню Fluid Effects пункты Pond => Create Pond (Пруд => Создать пруд) - рис. 16.71. На сцене появится двумерная жидкость. 2. Не снимая выделения с эффекта, откройте окно Attribute Editor, нажав клавиши Ctrl+a. Перейдите на вкладку pondShapel (рис. 16.72). В разделе Shading измените цвет, непрозрачность и самосвечение, а также другие свойства пруда. В данном примере используются установки по умолчанию.
468 Динамика Давайте придадим движение водяной глади. Для этого требуется создать след, который будет изменять поверхность пруда.
я 3 Create 3D CoMettor и*И EmKWr Q*et»2DCor*aVwH*hEn*»er
Создание следа 1. Выделите пруд, который вы создали в предыдущем разделе. 2. Выберите в меню Fluid Effects пункты Pond c> Create Wake (Пруд => Создать след) - рис. 16.73. В центре пруда будет создан эмиттер жидкости сферической формы. 3. Не снимая выделения с эмиттера, откройте окно Attribute Editor, нажав клавиши Ctrl+a. Перейдите на вкладку PondWakeEmitterl.
Clear Infcal ЯвМ SeveSUterts... Create Cache Append to Cache Truncate Cache Delete Cache
Рис. 16.73. Выберете в меню Fluid Effects пункты Pond о- Create Wake
4. Откройте раздел Fluid Attributes и присвойте атрибуту Density/Voxel/Sec (Плотность/Воксель/Секунд) значение 1 (рис. 16.74). Значение атрибута Density/Voxel/Sec определяет силу (следовательно, размер) следа. По умолчанию его значение равно 5. Оно создает слишком глубокий след. 5. Щелкните по кнопке Play на панели управления анимацией, чтобы оценить результат. 6. Изменяйте значение атрибута Density/ Voxel/Sec, пока не добьетесь нужного эффекта.
Рис, 16.74. Измените атрибуты следа в окне Attribute Editor
Эффекты жидкости
469
Следы можно создавать и. на поверхности океана. Выполните действия, описанные в предыдущем разделе, но на шаге 2 выберите пункты меню Ocean Create Wake.
Рис. 16.75. Анимированныи объект движется через пруд, оставляя след на фарватере
Чтобы связать следы с объектами или лодками, выделите объект, затем в меню Fluid Effects выберите пункты Pond => Create Wake. Теперь эмиттер будет наследован объекту. Если вы анимируете объект, эмиттер создаст позади него динамический след в форме расходящейся буквы V (рис. 16.75).
УШЛТШ Анимация 271 вдоль пути 299 воспроизведение 273 камеры 399 канал 296 настройки 273 ограничение 294 отрезок 300 предварительный просмотр 308 скорость 279 управление 272 циклическая 292 Атрибут 17 NURBS 88 задание 86 изменение 22, 26, 87, 94 ключевой 70 полигоны 97 радиус 86
В Версия Maya 14 Вес 253 Вид 20 в перспективе 56 выбор камеры 75 ортогональный 56 откат 53 перемещение 52
поворот 53 приближение объекта 65 режимы просмотра 72 точка наблюдения 74 Визуализатор 396, 408 Hardware Render Buffer 414 Hardware Renderer 422 IPR 420 Mental Ray 428 Software Renderer 411 Vector Renderer 424 Визуализация 332, 406 аппаратная 395, 414, 422 векторная 424 граница 427 заливка 425 вид 409 глобальное освещение 429, 434 качество 407 отражение 418 пакетная 412, 423 последний сбор 429, 432 последовательности 410 преломление 419 программная 395 просмотр 413 размытие при движении 412 разрешение 406 светотени 428, 430 сглаживание 407 трассировка лучей 417,418
Предметный указатель [47 j] установки 408 энергия 434 Вексель 459 Выделение 109 Hypergraph 111 Ouliner 111 в иерархии 113 добавление ПО инвертирование ПО отмена 111 удаление ПО Выравнивание 148, 156, 162 нескольких объектов 163, 165 нескольких точек 166 равномерное распределение 164 точки 166
Геометрия 39 «Горячая» клавиша 48 создание 49 Группа преобразование 152 создание 151 Группирование 148, 150, 151 разгруппирование 152
д Деформатор 310 Bend 312 Sculpt 325 Sine 314 Squash 317 Twist 319 Wave 316 Wire 322 без фиксатора 323 с фиксатором 324 нелинейный 311 отображение 326 параметры 311 скрытие 326 Динамика 435
Иерархия 29, 33, 155, 235 объекты по умолчанию 33 развернуть 32 Инструмент 3D Paint 384 заливка 385 Align Objects 163 Align Tool 165 Attribute Paint 258, 453 редактирование веса точек 259 Birail 185 Chamfer Vertex 213 Cut Face 208 CV Curve 175 Duplicate 136 Duplicate with Transform 146 Edit 263 EP Curve 175 Extrude Face 199 Vertex 204 IK Handle Tool 246, 248 IK_Spline Handle Tool 249 Insert Joint Tool 242 Joint Tool 237 Lasso Selection 135 Move 128 Paint Fluids Tool 461 Particle Tool 436 Pencil Curve 176 Point-to-Point Snap Align 166 Poke Faces 210 Reduce 219 Rotate 131 Scale 129 Show Manipulator 133 Smooth 216 Smooth Proxy 214 Snap Align 157 Snap Together 157 Split Polygon 205 Subdivide 215
472 Maya 5 для Windows и Macintosh Trim Tool 190 Wedge Face 211 Wire Tool 323 Интерфейс 51 изменение 56 скрытие/отображение элементов 61 схема окон 58, 60 История создания 34 включение и выключение 35 удаление 36 узлы 35 Источник света 334 атрибуты 335 затухание 336 интенсивность 335 карта 348 направленный 341 объемный 346 подсветка 337 привязывание 350 прожектор 344 особые атрибуты 345 просмотр сцены 349 протяженный 340 точечный 342 цвет 335
Камера анимация 399 вдоль пути 403 окружающая среда 405 плоскость изображения 405 поворот 402 преобразование 400 с наведением 398 следование 401 создание 397 фокусное расстояние 404 Каркас 90 Касательная фиксированная 285
Кинематика обратная 244 IK-манипулятор 246 использование кластеров 251 сплайн 249 прямая 236 Кластер 253 изменение веса 258, 259 создать 256 Ключевой кадр 271 касательная 283 изменение 286 копирование 288, 289 масштабирование 290 метка 274 видимость 280 редактирование 276 создание 274 автоматически 273 Команда Assign Material to Selection 367 Assign Textures 385 Attach to Motion Path 299 Boundary 186 Center Pivot 106 Convert Selection to Faces 198 Create 82 Create Character Set 301 Create Cluster 251 Curve Fillet 178 Detach Curves 180 Disconnect Joint 243 Duplicate, Make Copy Soft 451 Extrude 183 Full Crease Edge/Vertex 233 Full Crease.Edge/Vertex 234 Get Fluid Example 463 Ghost Selected 297 Graph Materials on Selected Objects 371 Group 151 Grow Selection Region 198 Loft 182
Предметный указатель 473~| Look Through Selected 348, 397 Make Boats 465 Make Collide 447 Move 128 Move and Sew UVs 391 Open/Close Curves 179 Parent 155 Planar 184 Redo Previous Render 340 Refine 225 Remove Joint 242 Render 413 Render the Current Frame 426 Reverse Curve Direction 176 Rotate 131 Scale 129 Select Camera 400 Show Batch Render 413 Shrink Selection Region 198 Template 121 Text 100 Ungroup 152 Unparent 156 Компонент 116 Контейнер 458 двумерный 458 редактирование 461 трехмерный 458 Кость 238 Кривая Безье 168 компоненты 169 направление 171 обращение 176 начальная точка 171 проецирование 190 - профильная 174 разбиение 180 размыкание/замыкание 179 рисование на поверхности 188 создание 170 степень 173
Л
Лофтинг 99
м Маска выбора 108 Маска выделения 109, 112 режим Component 116 Hierarchy 112 Object 114 Материал 361, 365 атрибуты 365 блик 360 накаливание 361 прозрачность 366, 377 рельеф 366, 378 Меню Animate 297 Character 301 Create 83 Deform 256, 307, 312 Display 61, 120, 196, 237 Dynamics 435 Edit 137 Edit Curves 176 Edit NURBS 190 Edit Polygons 198 Effects 455 Fields 445 File 337 Fluid Effects 461 Hotbox 14, 21, 27 отображение и скрытие 66 отображение наборов 67 Lighting/Shading 350 Modify 153, 231 Paint 259 Panels 56, 397 Particles 438 Render 338 Shading 72
474 Maya 5 для Windows и Macintosh Show 63 Skeleton 237 Skin 262, 266 Soft/Rigid Bodies 449 Subdiv Surfaces 232 Surfaces 181 Texturing 381 View 74, 404 Window 70, 286 главное 20 дополнительные 65 контекстное 21, 68 наборы 65
Н Набор быстрого выделения 119 Наследование 148, 150, 154, 252 к суставам 254 разрыв 156 создание 155 Настройка 43 манипулятора 45 отмена действия 44 сброс 47 цветовая схема 47
Оболочка 261 мягкая 266 отделение 269 Объект NURBS 169 волна 316 вращение 131 выделение 109 добавление примечания 76, 124 зеркальное отражение 142 изгиб 312 изменение цвета 366 копирование 137 с историей 145 с простым перемещением 147 масштабирование 129
название изменение 103 присвоение 103 отображение 64, 121 перемещение 128 примитив 77 преобразование 125 скручивание 319 скрытие 64, 120 создание экземпляра 143 сплющивание 317 текстовый 99 частиц 436 создание 436 шаблон 121 снятие 122 Океан 464 лодка 465 плоскость предварительного просмотра 465 создание 464 Окно Align Objects Options 163 Animation Preferences 280 Artisan 452 Assign File Textures 385 Color Chooser 365 Colors 47 Create Reference 43 Create Render Node 370 Custom Polygon Display Options 197 Detach Curve Options 180 Duplicate Options 137 Export 41 Extrude Face Options 202 Extrude Options 184 Extrude Vertex Options 204 Import 42 Mirror Joint Options 240 Options 85 Playblast Options 309 Polygon Cut Face Tool Options 209 Polygon Smooth Options 217
Предметный указатель 475 Polygon Wedge Faces Options 212 Preferences 45 Render Globals 396, 408 Render View 332, 421 Revolve Options 181 Save Scene 39 Settings/Preferences 44 Text Curves Options 186 главное 20 Освещение 327 глобальное 434 Отрезок 300 преобразование 305 создание 302
П Панель 54 Create 348 инструментов 127 Персонаж 235, 300 подперсонаж 303 сегментированный 255 создание 301 Поверхность активирование 188 вращения 181 выдавливания 183 компоненты 169 на двух направляющих 185 на основе границ 186 плоская 184 Поверхность разделения 193, 221 выдавливание 228 выделение 222 детализирование 225 излом полный 233 частичный 232, 234 использование полигонов 230 компоненты 221 преобразование 231 режим 220 полигональный 227
уровень 220 отображения 224 сглаживания 222 Поле 443 настройка 444 привязывание 445 Полигон 192 выдавливание 199 вдоль пути 202 выделение 195 выталкивание 211 компонент 194 манипулятор 199, 210 область выделения 198 обратная сторона 196 показ 197 разбить 205 разделить 215 разрезать 209 разрешение 215 расклинить 212 сгладить 217 скос 214 текстурирование 387 уменьшение 218 Полигоны 90 компоненты 90 методы создания 90 основные операции 91 примитивы 91 разделения 91 Полка 22 Surfaces 84 добавление элемента 23, 85 скрытие 23 Помощь 49 поиск 50 указатель 50 Преобразование 25, 125 вращение 131 «горячие» клавиши 127 зеркальное отражение 136, 142 копирование 137
476 Maya 5 для Windows и Macintosh манипулятор 126 изменение размеров 128 масштабирование 129 ось 126 перемещение 128 сложное 139 точное значение 24 Привязка 156, 252, 261 жесткая изменение весов 264 рисование весов 269 создание 262 к кривой 160 к плоскости вида 160 к сетке 159 к точке 161 мягкая 266 поза 270 Примитив 77 NURBS 79 компоненты 80 полигональный 91 изменение 94 создание 92 создание 82 Hotbox 84 главное меню 83 полка 85 центр 82 Проект 36 определение 38 создание 37 Пруд 467 Путь 299
Рабочее окно 54 замена 56 разворачивание 64 Редактор Attribute Editor 26 скрытие и отображение 71 Bookmark Editor 74
Channel Box 25, 132 наборы атрибутов 70 отображение и скрытие 69 Component Editor 257 Dope Sheet 291 Dynamic Relationships Editor 457 создание связи 457 Graph Editor 283 Hotkey Editor 48 Hypergraph 29 Hypershade 330, 362 назначение материала 367 показ соединений 371 части окна 363 Layer Editor 69, 123 Outliner 33 Script Editor 412 Trax Editor 300 UV Texture Editor 387 Режим компонентов 256 редактирования центра трансформаций 139 Решетка 310, 320 Рисование 384
Сглаживание 72 Сетка 69 Система координат 19 Скелет 235 ответвление 238 Скругление 177 Слой 122 видимость 76, 124 режим 123 создание 123 удаление 124 Снимок 297 создание 297 Соединение 18 Сокращенные наборы Pick Mask 118 тонирование и сглаживание 73
Предметный указатель 477 Столкновение 447 Строка главного меню 20 помощи 24 состояния 20 Сустав 235, 262 зеркальное отображение 240 наследование 238 основной 235 отсоединение 243 перемещение 241 создание 237 удаление из иерархии 242 Сцена создание 38 сохранение 39
Текст 99 вырезка 101 на основе кривых 100 скошенный 187 Текстура 362 Bulge 378 Ramp 372 качество 383 конвертирование 394 плавающая 394 показ 370 проекционная 380 настройка 382 проецирование 368 процедурная 372 рельеф 379 фрактал 377 шов 391 Текстурирование NURBS 368 направление 368 размещение 371 полигон 387 автоматически 388 оболочка 390
Тело мягкое 448 изменение веса 451 целевая форма 450 твердое активное 448 задание имитации 449 пассивное 448 Тень 352 глубинная 354 атрибуты 356 зернистость 359 смещение 356 трассированная 356 атрибуты 359 цвет 355 Тонировщик 360 Ramp 375 многослойный 377 рельеф 378 рисованный эффект 375 Точка решетки 320
Узел 17 bump2d 379 Input 136, 144 make 81 motionPath 403 place2dTexture 371 place3dTexture 381 зависимости 31 преобразования 26 Ф
Файл
звуковой 281 импорт 42 рабочий 37 ссылка 43 сцены 36 экспорт объектов 41 Флексор 265 Форма перехода 308
478 Maya 5 для Windows и Macintosh
Центр трансформаций 105 изменение 105 центрирование 106
Частица 436 визуализация 439 аппаратная 440 изменение 439 программная 442 продолжительность жизни 438 размер 437 создание 436
Caustics 428 Channel Box 25, 69, 132 Character 300 Constraint 294
Decay 336 Deform 256 DMap 353 Dolly 52 Dope Sheet 291 Dynamic Relationships Editor 457 Dynamics 435
Эмиттер 438 Эффект 452 дым 453 жидкости 458 атрибуты 459, 462 контейнер 458 пример 463 молния 456 обломки 454 огонь 453 следование кривой 454
Edge 194 Emitter 438 Extrude 198 Face 194 Fillet 177 Final Gather 429 Flare 313 Flood 386 Fluid Effects 458 Focal Length 404
А
Ghosting 297 Global illumination 428 Graph Editor 283 Grid 69 Grouping 148
Align 156 Aligning 148 Artisan 384 Attribute Editor 26, 71 Attribute Paint 258 Auto Keyframe 275
В Backface Culling 197 Bend 312 Binding 252 Blend Shape 306
H Hypergraph 29, 148, 245 Hypershade 330, 362 I
IK handle 244 Image plane 405 Instance 137
Предметный указатель 479J
Joint 235
Layer Editor 69, 123 Light 334
M Material 361 MEL 16 Move 128 Mute Animation Channel 296
N NURBS 81, 168 0
Ocean 464 Outliner 33
Paint Effects 386 Paint Operation 258 Parenting 148, 252 Particles 436 Path 299 Pick Mask 108 Pick mask 151 Pivot 105 Playblast 309 Polygon 192 Pond 467
Rendering 395 Revolve 181 Rigid Body 449 Rotate 131
Scale 129 Sculpt 325 Shader 360 Shading 72 Shadow 352 Shelf 22 Show 51 Show Manipulator 132 Sine 314 Skeleton 235 Skin 261 Smooth 214 Snap 156, 277 Squash 317 Subdivision Surface 220
Template 121 Text 99 Time 272 Track 52 Trax Editor 300 Tumble 52 Twist 319
и UV 194, 388 UV Texture Editor 387
Quick Select Set 119
R Range 272 Raytrace 353 Ray tracing 416, 417 Render Globals 396
Vertex 194 View 74 Visor 386
w Wave 316
Книги издательства «ДМК Пресс» можно заказать в торгово-издательском холдинге «АЛЬЯНС-КНИГА» наложенным платежом, выслав открытку или письмо по почтовому адресу: 123242, Москва, а/я 20 или по электронному адресу:
[email protected]. При оформлении заказа следует указать адрес (полностью), по которому должны быть высланы книги; фамилию, имя и отчество получателя. Желательно также указать свой телефон и электронный адрес. Эти книги вы можете заказать и в Internet-магазине: www.dmk.ru, www.abook.ru. Оптовые закупки: тел. (095) 258-91-94, 258-91-95; электронный адрес
[email protected]. Денни Рядделл
Maya 5 для Windows и М