Sunday, 27 January 2013

Как измерить время выполнения секции кода в python

Пришлось реализовать замер времени выполнения кода и вспомнил один вариант на который когда-то натолкнулся. (К сожалению ссылку на оригинал потерял, но принцип очень простой).
Создаём класс с двумя переопределёнными методами:

import time

class Profiler(object):
    def __enter__(self):
        self._startTime = time.time()
        
    def __exit__(self, type, value, traceback):
        print "Elapsed time: {:.3f} sec".format(time.time() - self._startTime)


И далее в коде используем следующим образом:

with Profile() as p:
    // your code to be profiled here


Соответсвенно всё понятно из приведённого примера. При входе в конструкцию with объект создаётся, а при выходе гарантированно завершается. Даже при возникновении исключения.
Очень хорошая статья поясняющая детали.
Если есть ещё какие-нибудь красивые методы был бы рад о них услышать.

Friday, 26 October 2012

Устанговка плагина Blender UV island copy paste.

Windows.

Для работы плагина требуется python-igraph модуль.
На данный момент python-igraph существует собранный только под win32 архитектуру.
Поэтому пока пробуем плагин только с версией Blender под win32.
(Позже я попытаюсь его собрать и под win64.)
Скачиваем архив ICP-win-x32.zip.
Распаковываем его в C:\Users\Username\AppData\Roaming\Blender Foundation\Blender\2.64\scripts\addons\.

Linux.

Для пользователей linux всё немного сложнее, если в вашем дистрибутиве нет готового пакета для python-igraph (нужен под python 3.2). Но это не проблема.
В этом случае потребуется сама библиотека igraph и модуль python-igraph.
Скачиваем архив ICP.zip.
Распаковываем в ~/.config/blender/2.64/scripts/addons/.

Скачиваем архив igraph с исходниками отсюда.
Распаковываем архив, компилируем и устанавливаем.
tar zxvf igraph-0.6.tar.gz
cd igraph-0.6/
./configure
make
sudo make install

Скачиваем архив python-igraph с исходниками отсюда.
Распаковываем, собираем и устанавливаем.
tar zxvf python-igraph-0.6.tar.gz
cd python-igraph-0.6/
python3 setup.py build
sudo python3 setup.py install

После этого копируем сам модуль igraph (директорию с именем igraph со всем её содержимым)
из директории /usr/local/lib64/python3.2/site-packages/python_igraph-0.6-py3.2-linux-x86_64.egg/
в ~/.config/blender/2.64/scripts/addons/modules/.

Загружаем Blender и в разделе User Preferences/Addons находим в разделе Mesh плагин UV island copy paste. Ставим галочку и пробуем как описано в видео.


Если возникают какие-то вопросы или ошибки не стеснясь пишем тут или на мне на почту.

P.S. В виду особенностей представления внутренних данных в Blender этот плагин хорошо работает только на островах с замкнутым швом. Т.е. все вершины в острове должны быть уникальны и не должно быть раздвоенных вершин. В UV редакторе при выбранном режиме sticky selection mode - shared vertex у каждой вершины не должно быть пары. С этими ограничениями плагин можно использовать. (Если после выполнения плагина образовалась каша и какие-то вершины с копировались неправильно, то скорее всего шов не замкнут.) Таким образом плагин требует доработки в архитектуре. Работа продолжается...

Monday, 22 October 2012

Taa-daa! :) I`m proudly present my UV-islands copy-paste plug-in for Blender.
Demo video.


Link for add-on itself will be added soon.
Also I`ve opened bug report about strange behaviour of island select here.
From Blender community site.
Stacking of symmetrical geometry - often times geometry that is exactly the same we will want to use the same image/texture data to save memory however, aligning the uv islands so they exactly overlap can be tedious. This would allow automatic alignment of UV islands for mirrored/symmetrical geometry. 

P.S. (Update) Due to some internal data organization in Blender this add-on works well on closed seams only. It means that UV island must have all vertex unique and no vertex split up.  In UV editor with sticky selection mode set to shared vertex no vertex should have pair. Add-on can be used in real work but with previous restrictions. So it needs additional design changes for open seams. And work in progress...

P.S.S. For those who would like to use and test it in it's current state, installation instructions (in English) can be found here. Also installation instructions in Russian.

Friday, 31 August 2012

Рендер интерьера магазина для НечегоНадеть.Ru

По - Blender
Рендер - Cycles



Saturday, 11 August 2012

How to add support for svg icons in PySyde application

First and very important note - svg icons requires xml support
so we need to add next line in our code:

from PySide import QtSvg, QtXml

or add QtSvg4.dll and QtXml4.dll in your bin distribution folder. This will include needed libraries in your distribution if you use something like pyinstaller to make executables.

Copy "plugins/imageformats/qsvg4.dll" from your PySide installation folder to your distribution folder.

Add qt.conf file in your bin distribution folder.

[Paths]
Prefix = .
Binaries = .
Plugins = ../plugins
Translations = ../translations

Friday, 20 July 2012

WIP. Dreadnought.


Based on Warhammer 40000 imperial dreadnought look and feel.
Adding mesh details - finishing stage (only small changes and details). Totally less than 10k quads.
Rigging - finished.
Animation - in process.
UV mapping and texturing - not yet done.

Saturday, 14 July 2012

WebGL services to show your 3D models on.

Do you want to share you models with friends? Show your WIP and let spectators to view your model with different angles and in close details? You need only WebGL compatible browser*. I think you like it.

p3d.in
- 3D models in Wavefront (.obj) format
- diffuse, specular and normal (doesn't like bump maps) textures in jpg format not more than 1024x1024px
Sketchfab
- 3D models in Blender (.blend), Collada (.dae), Wavefront (.obj), OpenSceneGraph (.osg, osgt, osgb, ive), 3DS (.3ds), Lightwave (.lwo | .lws), Polygon File Format (.ply), Virtual Reality Modeling Language (.wrl), Open Inventor (.iv), Shape (.shp), Standard Tessellation Language (.stl), Biovision Hierarchy (.bvh), Open Flight (.flt), ac3d (.ac), DirectX (.x), Designer Workbench (.dw), 3DC point cloud (.3dc), carbon graphics Inc (.geo), Generic Tagged Arrays (.gta)

The quick summary - you can post your models in 3D, share it with friends and others. But all models should be prepared and engines renders models with sometimes seen artifacts. Do you know any other free WebGL services like those two? Please let me know in comments.

* Best results I met with Mozilla Firefox and Google Chrome browsers. Opera 12 isn't quite stable with WebGL.