Cycles: add dedicated UV Map node, easier to find and has convenient auto complete.
[blender.git] / intern / cycles / app / cycles_xml.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16
17 #include <stdio.h>
18
19 #include <sstream>
20 #include <algorithm>
21 #include <iterator>
22
23 #include "camera.h"
24 #include "film.h"
25 #include "graph.h"
26 #include "integrator.h"
27 #include "light.h"
28 #include "mesh.h"
29 #include "nodes.h"
30 #include "object.h"
31 #include "shader.h"
32 #include "scene.h"
33
34 #include "subd_mesh.h"
35 #include "subd_patch.h"
36 #include "subd_split.h"
37
38 #include "util_debug.h"
39 #include "util_foreach.h"
40 #include "util_path.h"
41 #include "util_transform.h"
42 #include "util_xml.h"
43
44 #include "cycles_xml.h"
45
46 CCL_NAMESPACE_BEGIN
47
48 /* XML reading state */
49
50 struct XMLReadState {
51         Scene *scene;           /* scene pointer */
52         Transform tfm;          /* current transform state */
53         bool smooth;            /* smooth normal state */
54         int shader;                     /* current shader */
55         string base;            /* base path to current file*/
56         float dicing_rate;      /* current dicing rate */
57         Mesh::DisplacementMethod displacement_method;
58 };
59
60 /* Attribute Reading */
61
62 static bool xml_read_bool(bool *value, pugi::xml_node node, const char *name)
63 {
64         pugi::xml_attribute attr = node.attribute(name);
65
66         if(attr) {
67                 *value = (string_iequals(attr.value(), "true")) || (atoi(attr.value()) != 0);
68                 return true;
69         }
70
71         return false;
72 }
73
74 static bool xml_read_int(int *value, pugi::xml_node node, const char *name)
75 {
76         pugi::xml_attribute attr = node.attribute(name);
77
78         if(attr) {
79                 *value = atoi(attr.value());
80                 return true;
81         }
82
83         return false;
84 }
85
86 static bool xml_read_int_array(vector<int>& value, pugi::xml_node node, const char *name)
87 {
88         pugi::xml_attribute attr = node.attribute(name);
89
90         if(attr) {
91                 vector<string> tokens;
92                 string_split(tokens, attr.value());
93
94                 foreach(const string& token, tokens)
95                         value.push_back(atoi(token.c_str()));
96
97                 return true;
98         }
99
100         return false;
101 }
102
103 static bool xml_read_float(float *value, pugi::xml_node node, const char *name)
104 {
105         pugi::xml_attribute attr = node.attribute(name);
106
107         if(attr) {
108                 *value = atof(attr.value());
109                 return true;
110         }
111
112         return false;
113 }
114
115 static bool xml_read_float_array(vector<float>& value, pugi::xml_node node, const char *name)
116 {
117         pugi::xml_attribute attr = node.attribute(name);
118
119         if(attr) {
120                 vector<string> tokens;
121                 string_split(tokens, attr.value());
122
123                 foreach(const string& token, tokens)
124                         value.push_back(atof(token.c_str()));
125
126                 return true;
127         }
128
129         return false;
130 }
131
132 static bool xml_read_float3(float3 *value, pugi::xml_node node, const char *name)
133 {
134         vector<float> array;
135
136         if(xml_read_float_array(array, node, name) && array.size() == 3) {
137                 *value = make_float3(array[0], array[1], array[2]);
138                 return true;
139         }
140
141         return false;
142 }
143
144 static bool xml_read_float3_array(vector<float3>& value, pugi::xml_node node, const char *name)
145 {
146         vector<float> array;
147
148         if(xml_read_float_array(array, node, name)) {
149                 for(size_t i = 0; i < array.size(); i += 3)
150                         value.push_back(make_float3(array[i+0], array[i+1], array[i+2]));
151
152                 return true;
153         }
154
155         return false;
156 }
157
158 static bool xml_read_float4(float4 *value, pugi::xml_node node, const char *name)
159 {
160         vector<float> array;
161
162         if(xml_read_float_array(array, node, name) && array.size() == 4) {
163                 *value = make_float4(array[0], array[1], array[2], array[3]);
164                 return true;
165         }
166
167         return false;
168 }
169
170 static bool xml_read_string(string *str, pugi::xml_node node, const char *name)
171 {
172         pugi::xml_attribute attr = node.attribute(name);
173
174         if(attr) {
175                 *str = attr.value();
176                 return true;
177         }
178
179         return false;
180 }
181
182 static bool xml_read_ustring(ustring *str, pugi::xml_node node, const char *name)
183 {
184         pugi::xml_attribute attr = node.attribute(name);
185
186         if(attr) {
187                 *str = ustring(attr.value());
188                 return true;
189         }
190
191         return false;
192 }
193
194 static bool xml_equal_string(pugi::xml_node node, const char *name, const char *value)
195 {
196         pugi::xml_attribute attr = node.attribute(name);
197
198         if(attr)
199                 return string_iequals(attr.value(), value);
200         
201         return false;
202 }
203
204 static bool xml_read_enum(ustring *str, ShaderEnum& enm, pugi::xml_node node, const char *name)
205 {
206         pugi::xml_attribute attr = node.attribute(name);
207
208         if(attr) {
209                 ustring ustr(attr.value());
210
211                 if(enm.exists(ustr)) {
212                         *str = ustr;
213                         return true;
214                 }
215                 else
216                         fprintf(stderr, "Unknown value \"%s\" for attribute \"%s\".\n", ustr.c_str(), name);
217         }
218
219         return false;
220 }
221
222 static ShaderSocketType xml_read_socket_type(pugi::xml_node node, const char *name)
223 {
224         pugi::xml_attribute attr = node.attribute(name);
225
226         if(attr) {
227                 string value = attr.value();
228                 if (string_iequals(value, "float"))
229                         return SHADER_SOCKET_FLOAT;
230                 else if (string_iequals(value, "int"))
231                         return SHADER_SOCKET_INT;
232                 else if (string_iequals(value, "color"))
233                         return SHADER_SOCKET_COLOR;
234                 else if (string_iequals(value, "vector"))
235                         return SHADER_SOCKET_VECTOR;
236                 else if (string_iequals(value, "point"))
237                         return SHADER_SOCKET_POINT;
238                 else if (string_iequals(value, "normal"))
239                         return SHADER_SOCKET_NORMAL;
240                 else if (string_iequals(value, "closure color"))
241                         return SHADER_SOCKET_CLOSURE;
242                 else if (string_iequals(value, "string"))
243                         return SHADER_SOCKET_STRING;
244                 else
245                         fprintf(stderr, "Unknown shader socket type \"%s\" for attribute \"%s\".\n", value.c_str(), name);
246         }
247         
248         return SHADER_SOCKET_UNDEFINED;
249 }
250
251 /* Film */
252
253 static void xml_read_film(const XMLReadState& state, pugi::xml_node node)
254 {
255         Film *film = state.scene->film;
256         
257         xml_read_float(&film->exposure, node, "exposure");
258
259         /* ToDo: Filter Type */
260         xml_read_float(&film->filter_width, node, "filter_width");
261 }
262
263 /* Integrator */
264
265 static void xml_read_integrator(const XMLReadState& state, pugi::xml_node node)
266 {
267         Integrator *integrator = state.scene->integrator;
268         
269         /* Branched Path */
270         bool branched = false;
271         xml_read_bool(&branched, node, "branched");
272
273         if(branched) {
274                 integrator->method = Integrator::BRANCHED_PATH;
275
276                 xml_read_int(&integrator->diffuse_samples, node, "diffuse_samples");
277                 xml_read_int(&integrator->glossy_samples, node, "glossy_samples");
278                 xml_read_int(&integrator->transmission_samples, node, "transmission_samples");
279                 xml_read_int(&integrator->ao_samples, node, "ao_samples");
280                 xml_read_int(&integrator->mesh_light_samples, node, "mesh_light_samples");
281                 xml_read_int(&integrator->subsurface_samples, node, "subsurface_samples");
282                 xml_read_int(&integrator->volume_samples, node, "volume_samples");
283                 xml_read_bool(&integrator->sample_all_lights_direct, node, "sample_all_lights_direct");
284                 xml_read_bool(&integrator->sample_all_lights_indirect, node, "sample_all_lights_indirect");
285         }
286         
287         /* Bounces */
288         xml_read_int(&integrator->min_bounce, node, "min_bounce");
289         xml_read_int(&integrator->max_bounce, node, "max_bounce");
290         
291         xml_read_int(&integrator->max_diffuse_bounce, node, "max_diffuse_bounce");
292         xml_read_int(&integrator->max_glossy_bounce, node, "max_glossy_bounce");
293         xml_read_int(&integrator->max_transmission_bounce, node, "max_transmission_bounce");
294         xml_read_int(&integrator->max_volume_bounce, node, "max_volume_bounce");
295         
296         /* Transparency */
297         xml_read_int(&integrator->transparent_min_bounce, node, "transparent_min_bounce");
298         xml_read_int(&integrator->transparent_max_bounce, node, "transparent_max_bounce");
299         xml_read_bool(&integrator->transparent_shadows, node, "transparent_shadows");
300         
301         /* Volume */
302         xml_read_int(&integrator->volume_homogeneous_sampling, node, "volume_homogeneous_sampling");
303         xml_read_float(&integrator->volume_step_size, node, "volume_step_size");
304         xml_read_int(&integrator->volume_max_steps, node, "volume_max_steps");
305         
306         /* Various Settings */
307         xml_read_bool(&integrator->no_caustics, node, "no_caustics");
308         xml_read_float(&integrator->filter_glossy, node, "filter_glossy");
309         
310         xml_read_int(&integrator->seed, node, "seed");
311         xml_read_float(&integrator->sample_clamp_direct, node, "sample_clamp_direct");
312         xml_read_float(&integrator->sample_clamp_indirect, node, "sample_clamp_indirect");
313 }
314
315 /* Camera */
316
317 static void xml_read_camera(const XMLReadState& state, pugi::xml_node node)
318 {
319         Camera *cam = state.scene->camera;
320
321         xml_read_int(&cam->width, node, "width");
322         xml_read_int(&cam->height, node, "height");
323
324         if(xml_read_float(&cam->fov, node, "fov"))
325                 cam->fov *= M_PI/180.0f;
326
327         xml_read_float(&cam->nearclip, node, "nearclip");
328         xml_read_float(&cam->farclip, node, "farclip");
329         xml_read_float(&cam->aperturesize, node, "aperturesize"); // 0.5*focallength/fstop
330         xml_read_float(&cam->focaldistance, node, "focaldistance");
331         xml_read_float(&cam->shuttertime, node, "shuttertime");
332
333         if(xml_equal_string(node, "type", "orthographic"))
334                 cam->type = CAMERA_ORTHOGRAPHIC;
335         else if(xml_equal_string(node, "type", "perspective"))
336                 cam->type = CAMERA_PERSPECTIVE;
337         else if(xml_equal_string(node, "type", "panorama"))
338                 cam->type = CAMERA_PANORAMA;
339
340         if(xml_equal_string(node, "panorama_type", "equirectangular"))
341                 cam->panorama_type = PANORAMA_EQUIRECTANGULAR;
342         else if(xml_equal_string(node, "panorama_type", "fisheye_equidistant"))
343                 cam->panorama_type = PANORAMA_FISHEYE_EQUIDISTANT;
344         else if(xml_equal_string(node, "panorama_type", "fisheye_equisolid"))
345                 cam->panorama_type = PANORAMA_FISHEYE_EQUISOLID;
346
347         xml_read_float(&cam->fisheye_fov, node, "fisheye_fov");
348         xml_read_float(&cam->fisheye_lens, node, "fisheye_lens");
349
350         xml_read_float(&cam->sensorwidth, node, "sensorwidth");
351         xml_read_float(&cam->sensorheight, node, "sensorheight");
352
353         cam->matrix = state.tfm;
354
355         cam->need_update = true;
356         cam->update();
357 }
358
359 /* Shader */
360
361 static string xml_socket_name(const char *name)
362 {
363         string sname = name;
364         size_t i;
365
366         while((i = sname.find(" ")) != string::npos)
367                 sname.replace(i, 1, "");
368         
369         return sname;
370 }
371
372 static void xml_read_shader_graph(const XMLReadState& state, Shader *shader, pugi::xml_node graph_node)
373 {
374         ShaderGraph *graph = new ShaderGraph();
375
376         map<string, ShaderNode*> nodemap;
377
378         nodemap["output"] = graph->output();
379
380         for(pugi::xml_node node = graph_node.first_child(); node; node = node.next_sibling()) {
381                 ShaderNode *snode = NULL;
382
383                 if(string_iequals(node.name(), "image_texture")) {
384                         ImageTextureNode *img = new ImageTextureNode();
385
386                         xml_read_string(&img->filename, node, "src");
387                         img->filename = path_join(state.base, img->filename);
388                         
389                         xml_read_enum(&img->color_space, ImageTextureNode::color_space_enum, node, "color_space");
390                         xml_read_enum(&img->projection, ImageTextureNode::projection_enum, node, "projection");
391                         xml_read_float(&img->projection_blend, node, "projection_blend");
392
393                         snode = img;
394                 }
395                 else if(string_iequals(node.name(), "environment_texture")) {
396                         EnvironmentTextureNode *env = new EnvironmentTextureNode();
397
398                         xml_read_string(&env->filename, node, "src");
399                         env->filename = path_join(state.base, env->filename);
400                         
401                         xml_read_enum(&env->color_space, EnvironmentTextureNode::color_space_enum, node, "color_space");
402                         xml_read_enum(&env->projection, EnvironmentTextureNode::projection_enum, node, "projection");
403
404                         snode = env;
405                 }
406                 else if(string_iequals(node.name(), "osl_shader")) {
407                         OSLScriptNode *osl = new OSLScriptNode();
408
409                         /* Source */
410                         xml_read_string(&osl->filepath, node, "src");
411                         if(path_is_relative(osl->filepath)) {
412                                 osl->filepath = path_join(state.base, osl->filepath);
413                         }
414
415                         /* Generate inputs/outputs from node sockets
416                          *
417                          * Note: ShaderInput/ShaderOutput store shallow string copies only!
418                          * Socket names must be stored in the extra lists instead. */
419                         /* read input values */
420                         for(pugi::xml_node param = node.first_child(); param; param = param.next_sibling()) {
421                                 if (string_iequals(param.name(), "input")) {
422                                         string name;
423                                         if (!xml_read_string(&name, param, "name"))
424                                                 continue;
425                                         
426                                         ShaderSocketType type = xml_read_socket_type(param, "type");
427                                         if (type == SHADER_SOCKET_UNDEFINED)
428                                                 continue;
429                                         
430                                         osl->input_names.push_back(ustring(name));
431                                         osl->add_input(osl->input_names.back().c_str(), type);
432                                 }
433                                 else if (string_iequals(param.name(), "output")) {
434                                         string name;
435                                         if (!xml_read_string(&name, param, "name"))
436                                                 continue;
437                                         
438                                         ShaderSocketType type = xml_read_socket_type(param, "type");
439                                         if (type == SHADER_SOCKET_UNDEFINED)
440                                                 continue;
441                                         
442                                         osl->output_names.push_back(ustring(name));
443                                         osl->add_output(osl->output_names.back().c_str(), type);
444                                 }
445                         }
446                         
447                         snode = osl;
448                 }
449                 else if(string_iequals(node.name(), "sky_texture")) {
450                         SkyTextureNode *sky = new SkyTextureNode();
451                         
452                         xml_read_enum(&sky->type, SkyTextureNode::type_enum, node, "type");
453                         xml_read_float3(&sky->sun_direction, node, "sun_direction");
454                         xml_read_float(&sky->turbidity, node, "turbidity");
455                         xml_read_float(&sky->ground_albedo, node, "ground_albedo");
456                         
457                         snode = sky;
458                 }
459                 else if(string_iequals(node.name(), "noise_texture")) {
460                         snode = new NoiseTextureNode();
461                 }
462                 else if(string_iequals(node.name(), "checker_texture")) {
463                         snode = new CheckerTextureNode();
464                 }
465                 else if(string_iequals(node.name(), "brick_texture")) {
466                         BrickTextureNode *brick = new BrickTextureNode();
467
468                         xml_read_float(&brick->offset, node, "offset");
469                         xml_read_int(&brick->offset_frequency, node, "offset_frequency");
470                         xml_read_float(&brick->squash, node, "squash");
471                         xml_read_int(&brick->squash_frequency, node, "squash_frequency");
472
473                         snode = brick;
474                 }
475                 else if(string_iequals(node.name(), "gradient_texture")) {
476                         GradientTextureNode *blend = new GradientTextureNode();
477                         xml_read_enum(&blend->type, GradientTextureNode::type_enum, node, "type");
478                         snode = blend;
479                 }
480                 else if(string_iequals(node.name(), "voronoi_texture")) {
481                         VoronoiTextureNode *voronoi = new VoronoiTextureNode();
482                         xml_read_enum(&voronoi->coloring, VoronoiTextureNode::coloring_enum, node, "coloring");
483                         snode = voronoi;
484                 }
485                 else if(string_iequals(node.name(), "musgrave_texture")) {
486                         MusgraveTextureNode *musgrave = new MusgraveTextureNode();
487                         xml_read_enum(&musgrave->type, MusgraveTextureNode::type_enum, node, "type");
488                         snode = musgrave;
489                 }
490                 else if(string_iequals(node.name(), "magic_texture")) {
491                         MagicTextureNode *magic = new MagicTextureNode();
492                         xml_read_int(&magic->depth, node, "depth");
493                         snode = magic;
494                 }
495                 else if(string_iequals(node.name(), "noise_texture")) {
496                         NoiseTextureNode *dist = new NoiseTextureNode();
497                         snode = dist;
498                 }
499                 else if(string_iequals(node.name(), "wave_texture")) {
500                         WaveTextureNode *wave = new WaveTextureNode();
501                         xml_read_enum(&wave->type, WaveTextureNode::type_enum, node, "type");
502                         snode = wave;
503                 }
504                 else if(string_iequals(node.name(), "normal")) {
505                         NormalNode *normal = new NormalNode();
506                         xml_read_float3(&normal->direction, node, "direction");
507                         snode = normal;
508                 }
509                 else if(string_iequals(node.name(), "mapping")) {
510                         snode = new MappingNode();
511                 }
512                 else if(string_iequals(node.name(), "ward_bsdf")) {
513                         snode = new WardBsdfNode();
514                 }
515                 else if(string_iequals(node.name(), "diffuse_bsdf")) {
516                         snode = new DiffuseBsdfNode();
517                 }
518                 else if(string_iequals(node.name(), "translucent_bsdf")) {
519                         snode = new TranslucentBsdfNode();
520                 }
521                 else if(string_iequals(node.name(), "transparent_bsdf")) {
522                         snode = new TransparentBsdfNode();
523                 }
524                 else if(string_iequals(node.name(), "velvet_bsdf")) {
525                         snode = new VelvetBsdfNode();
526                 }
527                 else if(string_iequals(node.name(), "toon_bsdf")) {
528                         ToonBsdfNode *toon = new ToonBsdfNode();
529                         xml_read_enum(&toon->component, ToonBsdfNode::component_enum, node, "component");
530                         snode = toon;
531                 }
532                 else if(string_iequals(node.name(), "glossy_bsdf")) {
533                         GlossyBsdfNode *glossy = new GlossyBsdfNode();
534                         xml_read_enum(&glossy->distribution, GlossyBsdfNode::distribution_enum, node, "distribution");
535                         snode = glossy;
536                 }
537                 else if(string_iequals(node.name(), "glass_bsdf")) {
538                         GlassBsdfNode *diel = new GlassBsdfNode();
539                         xml_read_enum(&diel->distribution, GlassBsdfNode::distribution_enum, node, "distribution");
540                         snode = diel;
541                 }
542                 else if(string_iequals(node.name(), "refraction_bsdf")) {
543                         RefractionBsdfNode *diel = new RefractionBsdfNode();
544                         xml_read_enum(&diel->distribution, RefractionBsdfNode::distribution_enum, node, "distribution");
545                         snode = diel;
546                 }
547                 else if(string_iequals(node.name(), "hair_bsdf")) {
548                         HairBsdfNode *hair = new HairBsdfNode();
549                         xml_read_enum(&hair->component, HairBsdfNode::component_enum, node, "component");
550                         snode = hair;
551                 }
552                 else if(string_iequals(node.name(), "emission")) {
553                         EmissionNode *emission = new EmissionNode();
554                         xml_read_bool(&emission->total_power, node, "total_power");
555                         snode = emission;
556                 }
557                 else if(string_iequals(node.name(), "ambient_occlusion")) {
558                         snode = new AmbientOcclusionNode();
559                 }
560                 else if(string_iequals(node.name(), "background")) {
561                         snode = new BackgroundNode();
562                 }
563                 else if(string_iequals(node.name(), "absorption_volume")) {
564                         snode = new AbsorptionVolumeNode();
565                 }
566                 else if(string_iequals(node.name(), "scatter_volume")) {
567                         snode = new ScatterVolumeNode();
568                 }
569                 else if(string_iequals(node.name(), "subsurface_scattering")) {
570                         SubsurfaceScatteringNode *sss = new SubsurfaceScatteringNode();
571                         //xml_read_enum(&sss->falloff, SubsurfaceScatteringNode::falloff_enum, node, "falloff");
572                         snode = sss;
573                 }
574                 else if(string_iequals(node.name(), "geometry")) {
575                         snode = new GeometryNode();
576                 }
577                 else if(string_iequals(node.name(), "texture_coordinate")) {
578                         snode = new TextureCoordinateNode();
579                 }
580                 else if(string_iequals(node.name(), "light_path")) {
581                         snode = new LightPathNode();
582                 }
583                 else if(string_iequals(node.name(), "light_falloff")) {
584                         snode = new LightFalloffNode();
585                 }
586                 else if(string_iequals(node.name(), "object_info")) {
587                         snode = new ObjectInfoNode();
588                 }
589                 else if(string_iequals(node.name(), "particle_info")) {
590                         snode = new ParticleInfoNode();
591                 }
592                 else if(string_iequals(node.name(), "hair_info")) {
593                         snode = new HairInfoNode();
594                 }
595                 else if(string_iequals(node.name(), "value")) {
596                         ValueNode *value = new ValueNode();
597                         xml_read_float(&value->value, node, "value");
598                         snode = value;
599                 }
600                 else if(string_iequals(node.name(), "color")) {
601                         ColorNode *color = new ColorNode();
602                         xml_read_float3(&color->value, node, "value");
603                         snode = color;
604                 }
605                 else if(string_iequals(node.name(), "mix_closure")) {
606                         snode = new MixClosureNode();
607                 }
608                 else if(string_iequals(node.name(), "add_closure")) {
609                         snode = new AddClosureNode();
610                 }
611                 else if(string_iequals(node.name(), "invert")) {
612                         snode = new InvertNode();
613                 }
614                 else if(string_iequals(node.name(), "mix")) {
615                         MixNode *mix = new MixNode();
616                         xml_read_enum(&mix->type, MixNode::type_enum, node, "type");
617                         xml_read_bool(&mix->use_clamp, node, "use_clamp");
618                         snode = mix;
619                 }
620                 else if(string_iequals(node.name(), "gamma")) {
621                         snode = new GammaNode();
622                 }
623                 else if(string_iequals(node.name(), "brightness")) {
624                         snode = new BrightContrastNode();
625                 }
626                 else if(string_iequals(node.name(), "combine_rgb")) {
627                         snode = new CombineRGBNode();
628                 }
629                 else if(string_iequals(node.name(), "separate_rgb")) {
630                         snode = new SeparateRGBNode();
631                 }
632                 else if(string_iequals(node.name(), "combine_hsv")) {
633                         snode = new CombineHSVNode();
634                 }
635                 else if(string_iequals(node.name(), "separate_hsv")) {
636                         snode = new SeparateHSVNode();
637                 }
638                 else if(string_iequals(node.name(), "hsv")) {
639                         snode = new HSVNode();
640                 }
641                 else if(string_iequals(node.name(), "wavelength")) {
642                         snode = new WavelengthNode();
643                 }
644                 else if(string_iequals(node.name(), "blackbody")) {
645                         snode = new BlackbodyNode();
646                 }
647                 else if(string_iequals(node.name(), "attribute")) {
648                         AttributeNode *attr = new AttributeNode();
649                         xml_read_ustring(&attr->attribute, node, "attribute");
650                         snode = attr;
651                 }
652                 else if(string_iequals(node.name(), "uv_map")) {
653                         UVMapNode *uvm = new UVMapNode();
654                         xml_read_ustring(&uvm->attribute, node, "uv_map");
655                         snode = uvm;
656                 }
657                 else if(string_iequals(node.name(), "camera")) {
658                         snode = new CameraNode();
659                 }
660                 else if(string_iequals(node.name(), "fresnel")) {
661                         snode = new FresnelNode();
662                 }
663                 else if(string_iequals(node.name(), "layer_weight")) {
664                         snode = new LayerWeightNode();
665                 }
666                 else if(string_iequals(node.name(), "wireframe")) {
667                         WireframeNode *wire = new WireframeNode;
668                         xml_read_bool(&wire->use_pixel_size, node, "use_pixel_size");
669                         snode = wire;
670                 }
671                 else if(string_iequals(node.name(), "normal_map")) {
672                         NormalMapNode *nmap = new NormalMapNode;
673                         xml_read_ustring(&nmap->attribute, node, "attribute");
674                         xml_read_enum(&nmap->space, NormalMapNode::space_enum, node, "space");
675                         snode = nmap;
676                 }
677                 else if(string_iequals(node.name(), "tangent")) {
678                         TangentNode *tangent = new TangentNode;
679                         xml_read_ustring(&tangent->attribute, node, "attribute");
680                         xml_read_enum(&tangent->direction_type, TangentNode::direction_type_enum, node, "direction_type");
681                         xml_read_enum(&tangent->axis, TangentNode::axis_enum, node, "axis");
682                         snode = tangent;
683                 }
684                 else if(string_iequals(node.name(), "math")) {
685                         MathNode *math = new MathNode();
686                         xml_read_enum(&math->type, MathNode::type_enum, node, "type");
687                         xml_read_bool(&math->use_clamp, node, "use_clamp");
688                         snode = math;
689                 }
690                 else if(string_iequals(node.name(), "vector_math")) {
691                         VectorMathNode *vmath = new VectorMathNode();
692                         xml_read_enum(&vmath->type, VectorMathNode::type_enum, node, "type");
693                         snode = vmath;
694                 }
695                 else if(string_iequals(node.name(), "vector_transform")) {
696                         VectorTransformNode *vtransform = new VectorTransformNode();
697                         xml_read_enum(&vtransform->type, VectorTransformNode::type_enum, node, "type");
698                         xml_read_enum(&vtransform->convert_from, VectorTransformNode::convert_space_enum, node, "convert_from");
699                         xml_read_enum(&vtransform->convert_to, VectorTransformNode::convert_space_enum, node, "convert_to");
700                         snode = vtransform;
701                 }
702                 else if(string_iequals(node.name(), "connect")) {
703                         /* connect nodes */
704                         vector<string> from_tokens, to_tokens;
705
706                         string_split(from_tokens, node.attribute("from").value());
707                         string_split(to_tokens, node.attribute("to").value());
708
709                         if(from_tokens.size() == 2 && to_tokens.size() == 2) {
710                                 /* find nodes and sockets */
711                                 ShaderOutput *output = NULL;
712                                 ShaderInput *input = NULL;
713
714                                 if(nodemap.find(from_tokens[0]) != nodemap.end()) {
715                                         ShaderNode *fromnode = nodemap[from_tokens[0]];
716
717                                         foreach(ShaderOutput *out, fromnode->outputs)
718                                                 if(string_iequals(xml_socket_name(out->name), from_tokens[1]))
719                                                         output = out;
720
721                                         if(!output)
722                                                 fprintf(stderr, "Unknown output socket name \"%s\" on \"%s\".\n", from_tokens[1].c_str(), from_tokens[0].c_str());
723                                 }
724                                 else
725                                         fprintf(stderr, "Unknown shader node name \"%s\".\n", from_tokens[0].c_str());
726
727                                 if(nodemap.find(to_tokens[0]) != nodemap.end()) {
728                                         ShaderNode *tonode = nodemap[to_tokens[0]];
729
730                                         foreach(ShaderInput *in, tonode->inputs)
731                                                 if(string_iequals(xml_socket_name(in->name), to_tokens[1]))
732                                                         input = in;
733
734                                         if(!input)
735                                                 fprintf(stderr, "Unknown input socket name \"%s\" on \"%s\".\n", to_tokens[1].c_str(), to_tokens[0].c_str());
736                                 }
737                                 else
738                                         fprintf(stderr, "Unknown shader node name \"%s\".\n", to_tokens[0].c_str());
739
740                                 /* connect */
741                                 if(output && input)
742                                         graph->connect(output, input);
743                         }
744                         else
745                                 fprintf(stderr, "Invalid from or to value for connect node.\n");
746                 }
747                 else
748                         fprintf(stderr, "Unknown shader node \"%s\".\n", node.name());
749
750                 if(snode) {
751                         /* add to graph */
752                         graph->add(snode);
753
754                         /* add to map for name lookups */
755                         string name = "";
756                         xml_read_string(&name, node, "name");
757
758                         nodemap[name] = snode;
759
760                         /* read input values */
761                         for(pugi::xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute()) {
762                                 foreach(ShaderInput *in, snode->inputs) {
763                                         if(string_iequals(in->name, attr.name())) {
764                                                 switch(in->type) {
765                                                         case SHADER_SOCKET_FLOAT:
766                                                         case SHADER_SOCKET_INT:
767                                                                 xml_read_float(&in->value.x, node, attr.name());
768                                                                 break;
769                                                         case SHADER_SOCKET_COLOR:
770                                                         case SHADER_SOCKET_VECTOR:
771                                                         case SHADER_SOCKET_POINT:
772                                                         case SHADER_SOCKET_NORMAL:
773                                                                 xml_read_float3(&in->value, node, attr.name());
774                                                                 break;
775                                                         case SHADER_SOCKET_STRING:
776                                                                 xml_read_ustring( &in->value_string, node, attr.name() );
777                                                                 break;
778                                                         default:
779                                                                 break;
780                                                 }
781                                         }
782                                 }
783                         }
784                 }
785         }
786
787         shader->set_graph(graph);
788         shader->tag_update(state.scene);
789 }
790
791 static void xml_read_shader(const XMLReadState& state, pugi::xml_node node)
792 {
793         Shader *shader = new Shader();
794
795         xml_read_string(&shader->name, node, "name");
796         xml_read_bool(&shader->use_mis, node, "use_mis");
797         xml_read_bool(&shader->use_transparent_shadow, node, "use_transparent_shadow");
798         xml_read_bool(&shader->heterogeneous_volume, node, "heterogeneous_volume");
799
800         xml_read_shader_graph(state, shader, node);
801         state.scene->shaders.push_back(shader);
802 }
803
804 /* Background */
805
806 static void xml_read_background(const XMLReadState& state, pugi::xml_node node)
807 {
808         Shader *shader = state.scene->shaders[state.scene->default_background];
809         
810         xml_read_bool(&shader->heterogeneous_volume, node, "heterogeneous_volume");
811
812         xml_read_shader_graph(state, shader, node);
813 }
814
815 /* Mesh */
816
817 static Mesh *xml_add_mesh(Scene *scene, const Transform& tfm)
818 {
819         /* create mesh */
820         Mesh *mesh = new Mesh();
821         scene->meshes.push_back(mesh);
822
823         /* create object*/
824         Object *object = new Object();
825         object->mesh = mesh;
826         object->tfm = tfm;
827         scene->objects.push_back(object);
828
829         return mesh;
830 }
831
832 static void xml_read_mesh(const XMLReadState& state, pugi::xml_node node)
833 {
834         /* add mesh */
835         Mesh *mesh = xml_add_mesh(state.scene, state.tfm);
836         mesh->used_shaders.push_back(state.shader);
837
838         /* read state */
839         int shader = state.shader;
840         bool smooth = state.smooth;
841
842         mesh->displacement_method = state.displacement_method;
843
844         /* read vertices and polygons, RIB style */
845         vector<float3> P;
846         vector<int> verts, nverts;
847
848         xml_read_float3_array(P, node, "P");
849         xml_read_int_array(verts, node, "verts");
850         xml_read_int_array(nverts, node, "nverts");
851
852         if(xml_equal_string(node, "subdivision", "catmull-clark")) {
853                 /* create subd mesh */
854                 SubdMesh sdmesh;
855
856                 /* create subd vertices */
857                 for(size_t i = 0; i < P.size(); i++)
858                         sdmesh.add_vert(P[i]);
859
860                 /* create subd faces */
861                 int index_offset = 0;
862
863                 for(size_t i = 0; i < nverts.size(); i++) {
864                         if(nverts[i] == 4) {
865                                 int v0 = verts[index_offset + 0];
866                                 int v1 = verts[index_offset + 1];
867                                 int v2 = verts[index_offset + 2];
868                                 int v3 = verts[index_offset + 3];
869
870                                 sdmesh.add_face(v0, v1, v2, v3);
871                         }
872                         else {
873                                 for(int j = 0; j < nverts[i]-2; j++) {
874                                         int v0 = verts[index_offset];
875                                         int v1 = verts[index_offset + j + 1];
876                                         int v2 = verts[index_offset + j + 2];
877
878                                         sdmesh.add_face(v0, v1, v2);
879                                 }
880                         }
881
882                         index_offset += nverts[i];
883                 }
884
885                 /* finalize subd mesh */
886                 sdmesh.finish();
887
888                 /* parameters */
889                 SubdParams sdparams(mesh, shader, smooth);
890                 xml_read_float(&sdparams.dicing_rate, node, "dicing_rate");
891
892                 DiagSplit dsplit(sdparams);
893                 sdmesh.tessellate(&dsplit);
894         }
895         else {
896                 /* create vertices */
897                 mesh->verts = P;
898
899                 /* create triangles */
900                 int index_offset = 0;
901
902                 for(size_t i = 0; i < nverts.size(); i++) {
903                         for(int j = 0; j < nverts[i]-2; j++) {
904                                 int v0 = verts[index_offset];
905                                 int v1 = verts[index_offset + j + 1];
906                                 int v2 = verts[index_offset + j + 2];
907
908                                 assert(v0 < (int)P.size());
909                                 assert(v1 < (int)P.size());
910                                 assert(v2 < (int)P.size());
911
912                                 mesh->add_triangle(v0, v1, v2, shader, smooth);
913                         }
914
915                         index_offset += nverts[i];
916                 }
917         }
918
919         /* temporary for test compatibility */
920         mesh->attributes.remove(ATTR_STD_VERTEX_NORMAL);
921 }
922
923 /* Patch */
924
925 static void xml_read_patch(const XMLReadState& state, pugi::xml_node node)
926 {
927         /* read patch */
928         Patch *patch = NULL;
929
930         vector<float3> P;
931         xml_read_float3_array(P, node, "P");
932
933         if(xml_equal_string(node, "type", "bilinear")) {
934                 /* bilinear patch */
935                 if(P.size() == 4) {
936                         LinearQuadPatch *bpatch = new LinearQuadPatch();
937
938                         for(int i = 0; i < 4; i++)
939                                 P[i] = transform_point(&state.tfm, P[i]);
940                         memcpy(bpatch->hull, &P[0], sizeof(bpatch->hull));
941
942                         patch = bpatch;
943                 }
944                 else
945                         fprintf(stderr, "Invalid number of control points for bilinear patch.\n");
946         }
947         else if(xml_equal_string(node, "type", "bicubic")) {
948                 /* bicubic patch */
949                 if(P.size() == 16) {
950                         BicubicPatch *bpatch = new BicubicPatch();
951
952                         for(int i = 0; i < 16; i++)
953                                 P[i] = transform_point(&state.tfm, P[i]);
954                         memcpy(bpatch->hull, &P[0], sizeof(bpatch->hull));
955
956                         patch = bpatch;
957                 }
958                 else
959                         fprintf(stderr, "Invalid number of control points for bicubic patch.\n");
960         }
961         else
962                 fprintf(stderr, "Unknown patch type.\n");
963
964         if(patch) {
965                 /* add mesh */
966                 Mesh *mesh = xml_add_mesh(state.scene, transform_identity());
967
968                 mesh->used_shaders.push_back(state.shader);
969
970                 /* split */
971                 SubdParams sdparams(mesh, state.shader, state.smooth);
972                 xml_read_float(&sdparams.dicing_rate, node, "dicing_rate");
973
974                 DiagSplit dsplit(sdparams);
975                 dsplit.split_quad(patch);
976
977                 delete patch;
978
979                 /* temporary for test compatibility */
980                 mesh->attributes.remove(ATTR_STD_VERTEX_NORMAL);
981         }
982 }
983
984 /* Light */
985
986 static void xml_read_light(const XMLReadState& state, pugi::xml_node node)
987 {
988         Light *light = new Light();
989         light->shader = state.shader;
990
991         /* Light Type
992          * 0: Point, 1: Sun, 3: Area, 5: Spot */
993         int type = 0;
994         xml_read_int(&type, node, "type");
995         light->type = (LightType)type;
996
997         /* Spot Light */
998         xml_read_float(&light->spot_angle, node, "spot_angle");
999         xml_read_float(&light->spot_smooth, node, "spot_smooth");
1000
1001         /* Area Light */
1002         xml_read_float(&light->sizeu, node, "sizeu");
1003         xml_read_float(&light->sizev, node, "sizev");
1004         xml_read_float3(&light->axisu, node, "axisu");
1005         xml_read_float3(&light->axisv, node, "axisv");
1006         
1007         /* Generic */
1008         xml_read_float(&light->size, node, "size");
1009         xml_read_float3(&light->dir, node, "dir");
1010         xml_read_float3(&light->co, node, "P");
1011         light->co = transform_point(&state.tfm, light->co);
1012
1013         state.scene->lights.push_back(light);
1014 }
1015
1016 /* Transform */
1017
1018 static void xml_read_transform(pugi::xml_node node, Transform& tfm)
1019 {
1020         if(node.attribute("matrix")) {
1021                 vector<float> matrix;
1022                 if(xml_read_float_array(matrix, node, "matrix") && matrix.size() == 16)
1023                         tfm = tfm * transform_transpose((*(Transform*)&matrix[0]));
1024         }
1025
1026         if(node.attribute("translate")) {
1027                 float3 translate = make_float3(0.0f, 0.0f, 0.0f);
1028                 xml_read_float3(&translate, node, "translate");
1029                 tfm = tfm * transform_translate(translate);
1030         }
1031
1032         if(node.attribute("rotate")) {
1033                 float4 rotate = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
1034                 xml_read_float4(&rotate, node, "rotate");
1035                 tfm = tfm * transform_rotate(rotate.x*M_PI/180.0f, make_float3(rotate.y, rotate.z, rotate.w));
1036         }
1037
1038         if(node.attribute("scale")) {
1039                 float3 scale = make_float3(0.0f, 0.0f, 0.0f);
1040                 xml_read_float3(&scale, node, "scale");
1041                 tfm = tfm * transform_scale(scale);
1042         }
1043 }
1044
1045 /* State */
1046
1047 static void xml_read_state(XMLReadState& state, pugi::xml_node node)
1048 {
1049         /* read shader */
1050         string shadername;
1051
1052         if(xml_read_string(&shadername, node, "shader")) {
1053                 int i = 0;
1054                 bool found = false;
1055
1056                 foreach(Shader *shader, state.scene->shaders) {
1057                         if(shader->name == shadername) {
1058                                 state.shader = i;
1059                                 found = true;
1060                                 break;
1061                         }
1062
1063                         i++;
1064                 }
1065
1066                 if(!found)
1067                         fprintf(stderr, "Unknown shader \"%s\".\n", shadername.c_str());
1068         }
1069
1070         xml_read_float(&state.dicing_rate, node, "dicing_rate");
1071
1072         /* read smooth/flat */
1073         if(xml_equal_string(node, "interpolation", "smooth"))
1074                 state.smooth = true;
1075         else if(xml_equal_string(node, "interpolation", "flat"))
1076                 state.smooth = false;
1077
1078         /* read displacement method */
1079         if(xml_equal_string(node, "displacement_method", "true"))
1080                 state.displacement_method = Mesh::DISPLACE_TRUE;
1081         else if(xml_equal_string(node, "displacement_method", "bump"))
1082                 state.displacement_method = Mesh::DISPLACE_BUMP;
1083         else if(xml_equal_string(node, "displacement_method", "both"))
1084                 state.displacement_method = Mesh::DISPLACE_BOTH;
1085 }
1086
1087 /* Scene */
1088
1089 static void xml_read_include(const XMLReadState& state, const string& src);
1090
1091 static void xml_read_scene(const XMLReadState& state, pugi::xml_node scene_node)
1092 {
1093         for(pugi::xml_node node = scene_node.first_child(); node; node = node.next_sibling()) {
1094                 if(string_iequals(node.name(), "film")) {
1095                         xml_read_film(state, node);
1096                 }
1097                 else if(string_iequals(node.name(), "integrator")) {
1098                         xml_read_integrator(state, node);
1099                 }
1100                 else if(string_iequals(node.name(), "camera")) {
1101                         xml_read_camera(state, node);
1102                 }
1103                 else if(string_iequals(node.name(), "shader")) {
1104                         xml_read_shader(state, node);
1105                 }
1106                 else if(string_iequals(node.name(), "background")) {
1107                         xml_read_background(state, node);
1108                 }
1109                 else if(string_iequals(node.name(), "mesh")) {
1110                         xml_read_mesh(state, node);
1111                 }
1112                 else if(string_iequals(node.name(), "patch")) {
1113                         xml_read_patch(state, node);
1114                 }
1115                 else if(string_iequals(node.name(), "light")) {
1116                         xml_read_light(state, node);
1117                 }
1118                 else if(string_iequals(node.name(), "transform")) {
1119                         XMLReadState substate = state;
1120
1121                         xml_read_transform(node, substate.tfm);
1122                         xml_read_scene(substate, node);
1123                 }
1124                 else if(string_iequals(node.name(), "state")) {
1125                         XMLReadState substate = state;
1126
1127                         xml_read_state(substate, node);
1128                         xml_read_scene(substate, node);
1129                 }
1130                 else if(string_iequals(node.name(), "include")) {
1131                         string src;
1132
1133                         if(xml_read_string(&src, node, "src"))
1134                                 xml_read_include(state, src);
1135                 }
1136                 else
1137                         fprintf(stderr, "Unknown node \"%s\".\n", node.name());
1138         }
1139 }
1140
1141 /* Include */
1142
1143 static void xml_read_include(const XMLReadState& state, const string& src)
1144 {
1145         /* open XML document */
1146         pugi::xml_document doc;
1147         pugi::xml_parse_result parse_result;
1148
1149         string path = path_join(state.base, src);
1150         parse_result = doc.load_file(path.c_str());
1151
1152         if(parse_result) {
1153                 XMLReadState substate = state;
1154                 substate.base = path_dirname(path);
1155
1156                 xml_read_scene(substate, doc);
1157         }
1158         else {
1159                 fprintf(stderr, "%s read error: %s\n", src.c_str(), parse_result.description());
1160                 exit(EXIT_FAILURE);
1161         }
1162 }
1163
1164 /* File */
1165
1166 void xml_read_file(Scene *scene, const char *filepath)
1167 {
1168         XMLReadState state;
1169
1170         state.scene = scene;
1171         state.tfm = transform_identity();
1172         state.shader = scene->default_surface;
1173         state.smooth = false;
1174         state.dicing_rate = 0.1f;
1175         state.base = path_dirname(filepath);
1176
1177         xml_read_include(state, path_filename(filepath));
1178
1179         scene->params.bvh_type = SceneParams::BVH_STATIC;
1180 }
1181
1182 CCL_NAMESPACE_END
1183