Что такое расширение файла map?

Shared Memory

You have probably heard of «Shared Memory» now and then. This terminology usually refers to a data block that is shared by more than one application that is running on one or more computer stations. There are several different implementations of shared memory solutions, hardware, software, or combined. This article is focused on MMF based shared memory design, which is an extension of what you’ve seen in the Simple IPC sample.

When you design a shared memory solution, some basic features are commonly required:

  • Shared memory shall be data oriented, i.e., all the data to be exchanged should be wrapped in a structure for easy access.
  • Access to the shared memory is transparent, i.e., using the shared memory as if you were using the data structure directly.
  • Access to the shared memory shall be protected to ensure data integrity.

The following code represents a limited implementation of a shared memory class in .NET 4:

using System;
using System.IO;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Threading;

namespace NetSharedMemory
{
    public class SharedMemory<T> where T: struct
    {
        
        public SharedMemory(string name, int size)
        {
            smName = name;
            smSize = size;
        }

        
        public bool Open()
        {
            try
            {
                
                mmf = MemoryMappedFile.CreateOrOpen(smName, smSize);
                
                
                accessor = mmf.CreateViewAccessor(, smSize, 
                               MemoryMappedFileAccess.ReadWrite);

                
                smLock = new Mutex(true, "SM_LOCK", out locked);
            }
            catch
            {
                return false;
            }

            return true;
        }

        public void Close()
        {
            accessor.Dispose();
            mmf.Dispose();
            smLock.Close();
        }

        public T Data
        {
            get 
            {
                T dataStruct;
                accessor.Read<T>(, out dataStruct);
                return dataStruct; 
            }
            set 
            {
                smLock.WaitOne();
                accessor.Write<T>(, ref value);
                smLock.ReleaseMutex();
            }
        }

        
        private string smName;
        private Mutex smLock;
        private int smSize;
        private bool locked;
        private MemoryMappedFile mmf;
        private MemoryMappedViewAccessor accessor;
    }
}

Now we write a sample application to use this class. First we create some data.

public struct Point 
{
    public int x;
    public int y;
}

public struct MyData
{
    public int myInt;
    public Point myPt;
}

To keep the code simple, I declared all attributes in the structures . In the real world, you should protect the data and expose them through properties. Anyway, now we write a class to use . The class shall read the data from the shared memory block, modify the data, and finally write the changes back to the shared memory.

class Program
{
    static void Main(string[] args)
    {
        SharedMemory<MyData> shmem = 
             new SharedMemory<MyData>("ShmemTest", 32);
        
        if(!shmem.Open()) return;

        MyData data = new MyData();
        
        
        data = shmem.Data;
        Console.WriteLine("{0}, {1}, {2}", 
            data.myInt, data.myPt.x, data.myPt.y);
       
        
        data.myInt = 1;
        data.myPt.x = 2;
        data.myPt.y = 3;

        
        shmem.Data = data;

        
        Console.ReadKey();

        
        shmem.Close();        
    }
}

The code is by all means very simple. Build the project «SharedMemoryClient». Run two instances of it. You will notice that the data the second instance reads contains some changes made by the first instance.

There are a number of places you should pay attention to:

  • is a generic (parameterized) class that takes a structure as the parameter to the class. That structure parameter is a place holder for the data to be shared.
  • When protecting the shared memory, we only lock writing to, not reading from, the data block. This is purely a practical consideration for the sake of performance. You may protect both reading and writing depending on applications.
  • The structure copy we performed is a shallow, not deep one. In other worlds, the data we exchange should not contain reference types. This makes sense as we have no knowledge of what the data block actually contains. Shallow copy is usually enough as shared memory is a data oriented, not object oriented design.

Common uses

Perhaps the most common use for a memory-mapped file is the process loader in most modern operating systems (including Microsoft Windows and Unix-like systems.) When a process is started, the operating system uses a memory mapped file to bring the executable file, along with any loadable modules, into memory for execution. Most memory-mapping systems use a technique called demand paging, where the file is loaded into physical memory in subsets (one page each), and only when that page is actually referenced. In the specific case of executable files, this permits the OS to selectively load only those portions of a process image that actually need to execute.

Another common use for memory-mapped files is to share memory between multiple processes. In modern protected mode operating systems, processes are generally not permitted to access memory space that is allocated for use by another process. (A program’s attempt to do so causes or segmentation violations.) There are a number of techniques available to safely share memory, and memory-mapped file I/O is one of the most popular. Two or more applications can simultaneously map a single physical file into memory and access this memory. For example, the Microsoft Windows operating system provides a mechanism for applications to memory-map a shared segment of the system’s page file itself and share data via this section.

Устранение неполадок при открытии файлов MAP

Общие проблемы с открытием файлов MAP

Valve Hammer Editor не установлен

Дважды щелкнув по файлу MAP вы можете увидеть системное диалоговое окно, в котором сообщается «Не удается открыть этот тип файла». В этом случае обычно это связано с тем, что на вашем компьютере не установлено Valve Hammer Editor для %%os%%. Так как ваша операционная система не знает, что делать с этим файлом, вы не сможете открыть его дважды щелкнув на него.

Совет: Если вам извстна другая программа, которая может открыть файл MAP, вы можете попробовать открыть данный файл, выбрав это приложение из списка возможных программ.

Установлена неправильная версия Valve Hammer Editor

В некоторых случаях у вас может быть более новая (или более старая) версия файла Quake Engine Map File, не поддерживаемая установленной версией приложения. При отсутствии правильной версии ПО Valve Hammer Editor (или любой из других программ, перечисленных выше), может потребоваться загрузить другую версию ПО или одного из других прикладных программных средств, перечисленных выше. Такая проблема чаще всего возникает при работе в более старой версии прикладного программного средства с файлом, созданным в более новой версии, который старая версия не может распознать.

Совет: Иногда вы можете получить общее представление о версии файла MAP, щелкнув правой кнопкой мыши на файл, а затем выбрав «Свойства» (Windows) или «Получить информацию» (Mac OSX).

Резюме: В любом случае, большинство проблем, возникающих во время открытия файлов MAP, связаны с отсутствием на вашем компьютере установленного правильного прикладного программного средства.

Даже если на вашем компьютере уже установлено Valve Hammer Editor или другое программное обеспечение, связанное с MAP, вы все равно можете столкнуться с проблемами во время открытия файлов Quake Engine Map File. Если проблемы открытия файлов MAP до сих пор не устранены, возможно, причина кроется в других проблемах, не позволяющих открыть эти файлы. Такие проблемы включают (представлены в порядке от наиболее до наименее распространенных):

Drawbacks

The major reason to choose memory mapped file I/O is performance. Nevertheless, there can be tradeoffs. The standard I/O approach is costly due to system call overhead and memory copying. The memory-mapped approach has its cost in —when a block of data is loaded in page cache, but is not yet mapped into the process’s virtual memory space. In some circumstances, memory mapped file I/O can be substantially slower than standard file I/O.

Another drawback of memory-mapped files relates to a given architecture’s address space: a file larger than the addressable space can have only portions mapped at a time, complicating reading it. For example, a 32-bit architecture such as Intel’s IA-32 can only directly address 4 GiB or smaller portions of files. An even smaller amount of addressable space is available to individual programs—typically in the range of 2 to 3 GiB, depending on the operating system kernel.

I/O errors on the underlying file (e.g. its removable drive is unplugged or optical media is ejected, disk full when writing, etc.) while accessing its mapped memory are reported to the application as the SIGSEGV/SIGBUS signals on POSIX, and the EXECUTE_IN_PAGE_ERROR structured exception on Windows. All code accessing mapped memory must be prepared to handle these errors, which don’t normally occur when accessing memory.

Only hardware architectures with an MMU can support memory-mapped files. On architectures without an MMU, the operating system can copy the entire file into memory when the request to map it is made, but this is extremely wasteful and slow if only a little bit of the file will be accessed, and can only work for files that will fit in available memory.

Platform support

Most modern operating systems or runtime environments support some form of memory-mapped file access. The function mmap(), which creates a mapping of a file given a file descriptor, starting location in the file, and a length, is part of the POSIX specification, so the wide variety of POSIX-compliant systems, such as UNIX, Linux, Mac OS X or OpenVMS, support a common mechanism for memory mapping files. The Microsoft Windows operating systems also support a group of API functions for this purpose, such as CreateFileMapping().

Some free portable implementations of memory-mapped files for Microsoft Windows and POSIX-compliant platforms are:

  • Boost.Interprocess, in Boost C++ Libraries
  • Boost.Iostreams, also in Boost C++ Libraries
  • Fmstream
  • Cpp-mmf

The Java programming language provides classes and methods to access memory mapped files, such as .

The D programming language supports memory mapped files in its standard library (std.mmfile module).

Ruby has a gem (library) called Mmap, which implements memory-mapped file objects.

Since version 1.6, Python has included a mmap module in its Standard Library. Details of the module vary according to whether the host platform is Windows or Unix-like.

For Perl there are several modules available for memory mapping files on the CPAN, such as Sys::Mmap and File::Map.

The J programming language has supported memory mapped files since at least 2005. It includes support for boxed array data, and single datatype files. Support can be loaded from ‘data/jmf’ J’s Jdb and JD database engines use memory mapped files for column stores.

About the Author

Jun Du

Architect
GuestLogix Inc.

Canada

Jun is an experienced software architect. He wrote his first computer code on the tape machine for a «super computer». The tape machine reads holes on the black pape tape as source code. When manually fixing code, you need a punch and tranparent tape. To delete code, you block holes or cut off a segment and glue two ends together. To change code, you block old holes and punch new holes. You already know how to add new code, don’t you? Anyway, that was his programming story in early 1980’s.
Jun completed university with the specialty in oceanography, and graduate study in meteorology. He obtained his Ph.D. in physics. Jun has worked in a number of different areas. Since mid-90’s, he has been working as a software professional in both military & commercial industries, including Visual Defence, Atlantis Systems International and Array Systems Computing.
Currently, Jun is an architect at GuestLogix, the global leader in providing onboard retail solutions for airlines and other travel industries. He is also the founder of Intribute Dynamics, a consulting firm specialized in software development. He has a personal blog site, although he is hardly able to keep it up to date.
In his spare time, Jun loves classic music, table tennis, and NBA games. During the summer, he enjoyes camping out to the north and fishing on wild lakes.

Резюме файла MAP

Эти файлы MAP можно просматривать с помощью тридцать шесть существующего (-их) прикладных (-ого) программных (-ого) средств (-а), как правило, Valve Hammer Editor, разработанного Valve. Оно связано с двадцать шесть основным (-и) типом (-ами) файла (-ов), но часто встречается в формате Quake Engine Map File.
Расширение файла MAP указано преимущественно в категории Game Files. В менее распространенных приложениях они также могут быть Uncommon Files или Data Files.

Расширение файла MAP можно просмотреть в Windows, Mac и Linux. Они поддерживаются в основном настольными компьютерами и некоторыми мобильными платформами.

Рейтинг популярности расширения файла MAP составляет «Низкий», что означает, что эти файлы, как правило, не встречаются в большинстве файловых хранилищ пользователя.

Mapmaker

open()

    int fd;

    fd = open("mapdemofile", O_RDWR);

In this example, we’ve opened the file for read/write access. You can
open it in whatever mode you want, but it has to match the mode
specified in the prot parameter to the mmap()
call, below.

To memory map a file, you use the mmap() system call, which is
defined as follows:

    void *mmap(void *addr, size_t len, int prot, int flags,
               int fildes, off_t off);

What a slew of parameters! Here they are, one at a time:

addr

This is the address we want the file mapped into. The best way to
use this is to set it to (caddr_t)0 and let the OS
choose it for you. If you tell it to use an address the OS doesn’t
like (for instance, if it’s not a multiple of the virtual memory page
size), it’ll give you an error.

len

This parameter is the length of the data we want to map into memory.
This can be any length you want. (Aside: if len not a
multiple of the virtual memory page size, you will get a blocksize that
is rounded up to that size. The extra bytes will be 0, and any changes
you make to them will not modify the file.)

prot

The «protection» argument allows you to specify what kind of access
this process has to the memory mapped region. This can be a bitwise-ORd
mixture of the following values: PROT_READ,
PROT_WRITE, and PROT_EXEC, for read, write, and
execute permissions, respectively. The value specified here must be
equivalent to the mode specified in the open() system call that
is used to get the file descriptor.

flags

There are just miscellaneous flags that can be set for the system
call. You’ll want to set it to MAP_SHARED if you’re planning
to share your changes to the file with other processes, or
MAP_PRIVATE otherwise. If you set it to the latter, your
process will get a copy of the mapped region, so any changes you make to
it will not be reflected in the original file—thus, other processes
will not be able to see them. We won’t talk about MAP_PRIVATE
here at all, since it doesn’t have much to do with IPC.

fildes

This is where you put that file descriptor you opened earlier.

off
This is the offset in the file that you want to start mapping from.
A restriction: this must be a multiple of the virtual memory page
size. This page size can be obtained with a call to
getpagesize().

As for return values, as you might have guessed, mmap() returns
-1 on error, and sets errno. Otherwise, it returns a
pointer to the start of the mapped data.

Anyway, without any further ado, we’ll do a short demo that maps the
second «page» of a file into memory. First we’ll open() it to
get the file descriptor, then we’ll use getpagesize() to get
the size of a virtual memory page and use this value for both the
len and the off. In this way, we’ll
start mapping at the second page, and map for one page’s length. (On my
Linux box, the page size is 4K.)

    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/mman.h>

    int fd, pagesize;
    char *data;

    fd = fopen("foo", O_RDONLY);
    pagesize = getpagesize();
    data = mmap((caddr_t)0, pagesize, PROT_READ, MAP_SHARED, fd, pagesize);

Once this code stretch has run, you can access the first byte of the
mapped section of file using data. Notice there’s a lot of
type conversion going on here. For instance, mmap() returns
caddr_t, but we treat it as a char*. Well, the fact is
that caddr_t usually is defined to be a char*, so
everything’s fine.

Also notice that we’ve mapped the file PROT_READ so we have
read-only access. Any attempt to write to the data (data =
'B'
, for example) will cause a segmentation violation.
Open the file O_RDWR with prot set to
PROT_READ|PROT_WRITE if you want read-write access to the data.

mmap

Скрыть рекламу в статье

mmap

Система UNIX предоставляет полезное средство, позволяющее программам совместно использовать память, и, к счастью, оно включено в версию 2.0 и более поздние версии ядра Linux. Функция (для отображения памяти) задает сегмент памяти, который может читаться двумя или несколькими программами и в который они могут записывать данные. Изменения, сделанные одной программой, видны всем остальным.

Вы можете применить то же самое средство для работы с файлами, заставив все содержимое файла на диске выглядеть как массив в памяти. Если файл состоит из записей, которые могут быть описаны структурами на языке С, вы сможете обновлять файл с помощью методов доступа к массиву структур.

Это становится возможным благодаря применению сегментов виртуальной памяти с набором особых прав доступа. Чтение из сегмента и запись в него заставляет операционную систему читать соответствующую часть файла на диске и писать данные в нее.

Функция mmap создает указатель на область памяти, ассоциированную с содержимым файла, доступ к которому осуществляется через открытый дескриптор файла.

Изменить начальную позицию порции данных файла, к которым выполняется обращение через совместно используемый сегмент, можно, передавая параметр . Открытый дескриптор файла задается в параметре . Объем данных, к которым возможен доступ (т. е. размер сегмента памяти), указывается в параметре .

Параметр можно использовать для запроса конкретного адреса памяти. Если он равен нулю, результирующий указатель формируется автоматически. Последний вариант рекомендуется, потому что в противном случае трудно добиться переносимости; диапазоны доступных адресов в разных системах отличаются.

Параметр используется для установки прав доступа к сегменту памяти. Он представляет собой результат поразрядной операции or, примененной к следующим константам:

? — сегмент может читаться;

? — в сегмент можно писать;

? — сегмент может выполняться;

? — к сегменту нет доступа.

Параметр контролирует, как изменения, сделанные программой в сегменте, отражаются в других местах; его возможные значения приведены в табл. 3.7.

Таблица 3.7

Константа Описание
Сегмент частный, изменения локальные
Изменения сегмента переносятся в файл
Сегмент должен располагаться по заданному адресу

Функция вызывает запись изменений в части или во всем сегменте памяти обратно а отображенный файл (или считывание из файла).

Корректируемая часть сегмента задается передачей начального адреса и размера . Параметр управляет способом выполнения корректировки с помощью вариантов, приведенных в табл. 3.8.

Таблица 3.8

Константа Описание
Выполнять запись асинхронно
Выполнять запись синхронно
Обновить другие отражения этого файла так, чтобы они содержали изменения, внесенные этим вызовом

Функция освобождает сегмент памяти.

В программе mmap.с из упражнения 3.5 показан файл из структур, которые будут корректироваться с помощью функции и обращений в стиле массива. Ядро Linux версий, меньших 2.0, не полностью поддерживает применение функции . Программа работает корректно в системе Sun Solaris и других системах.

Упражнение 3.5. Применение функции

1. Начните с определения структуры и создайте вариантов, в каждый из которых записывается собственный номер. Они будут добавлены в конец файла records.dat.

2. Далее измените целое значение записи с 43 на 143 и запишите его в строку 43-й записи.

3. Теперь отобразите записи в память и обратитесь к 43-й записи для того, чтобы изменить целое на 243 (и обновить строку записи), снова используя отображение в память.

В главе 13 вы встретитесь с еще одним средством совместного использования памяти — разделяемой памятью System V.

Оглавление книги

Points of Interest

The implementation of Shared Memory presented above does not fully meet the requirements of transparency, mainly due to the lack of support for pointer operations in C#. In native C++, overloading the operator «» would provide a better solution. Unfortunately, we couldn’t overload the C# operator «» as we do with the C++ operator «». As such, the combined use of property and structure copy is a somehow compromised solution.

As we’ve seen, there could be different implementations of MMF. C++ and C# implement MMF differently. Managed and unmanaged platforms also implement MMF differently. One question we haven’t addressed is: can .NET 4 applications exchange data with applications that were written and built in VC++ 6.0? The answer is yes. In Windows internals, MMF is a named kernel object, like a mutex. What really matters with MMF is its name, size of the memory it reserves, and offset of the memory address. Note that the size and offset are important because you want to ensure the data you are accessing is not truncated or otherwise corrupted!

Чем открыть файл в формате MD

Расширение MD является одним из самых распространенных и востребованных среди пользователей и может быть следующих основных исполнений:

MD файл (полн. Markdown) представляет собой универсальный скрипт текстовой разметки документа, сгенерированный Дж. Грубером в целях структурного редактирования текста с использованием минимального набора инструментов. Markdown может заимствовать некоторые средства форматирования текстовой информации, используемые в электронной переписке.

Другими словами, Markdown включает в себя интегрированный скрипт, устанавливающий каким образом будет отформатирована текстовая информация, например, позиционирование заголовков и подзаголовков, положение таблиц, шрифт и размер текста и.т.д.

Для корректного отображения информации на экране монитора, MD расширение должно пройти компиляцию парсером Markdown. Задекларировано большое многообразие различных исполнений Markdown, которые зачастую являются лишь частью систем управления в интернет-сети.

Основное практическое назначение MD формата – представление простой текстовой информации, которая впоследствии может быть легко транслирована в HTML (универсальный формат гипертекстовой разметки, используемый для представления веб-страниц).

Чаще обычного формат с разметкой Markdown используются в качестве текста лицензий на программное обеспечение, а также инструкций по применению с комментариями, например, Readme.md или changelog.md.

  • MD файл (полн. Machine Description) применяется в качестве идентификатора компьютерной машины. По своей структуре MD формат представляет собой набор данных, определяющий свойства и технические характеристики персонального компьютера, как сборочной единицы. Архитектура центрального процессора, набор команд и ключевых инструкций взаимодействия процессов, возможности оптимизации кода – это лишь самый незначительный перечень основных параметров, которые могут быть установлены в типовом MD файле.
  • MD формат (полн. MDCD Compressed Archive), используемый в качестве архиватора данных. MDCD — уникальная технология компрессии, основанная на 13-тибитном алгоритме LZW, и позволяющая достичь высокой степени сжатия. Однако, данный формат не получил широкого распространения в кругу рядовых пользователей.

Программы для открытия  MD файлов

В зависимости от своего практического назначения и конкретной модификации, MD расширение может быть сгенерировано и открыто для редактирования с использованием следующих программных комплексов:

Для случаев, когда MD файл представляет собой универсальный скрипт Markdown текстовой разметки документа, можно воспользоваться следующими утилитами и текстовыми редакторами:

Когда MD файл применяется в качестве идентификатора компьютерной машины (Machine Description) и по своей структуре представляет набор данных, определяющий свойства и технические характеристики персонального компьютера, могут быть использованы следующие утилиты:

Если при открытии расширения MD возникает ошибка, причины могут заключаться в следующем:

  • поврежден или инфицирован файл;
  • файл не связан с реестром ОС (выбрано некорректное приложение для воспроизведения или не произведена инсталляция конкретного плагина);
  • недостаточно ресурсов устройства или ОС;
  • поврежденные или устаревшие драйвера.

Конвертация MD в другие форматы

Несмотря на то, что MD расширение имеет большое число самых разнообразных исполнений и модификаций, его конвертация в другие форматы поддерживается только в ряде случаев, в частности:

Во всех остальных случаях преобразование формата не поддерживается. Попытки конвертации расширения в другой формат могут не только не дать никаких практических результатов, но и повредить исходный файл.

Почему именно MD и в чем его достоинства?

MD расширение является одним из самых востребованных среди обычных пользователей. Формат может выступать в качестве:

  • универсального скрипта Markdown текстовой разметки документа;
  • идентификатора компьютерной машины (Machine Description), определяющего свойства и технические характеристики персонального компьютера;
  • высокопроизводительного архиватора данных с высокой степенью сжатия;
  • репозитория данных, содержащего детальную информацию о финансовых сделках (транзакциях);
  • эмулятора игровой консоли Sega и представляет собой образ картриджа игры;
  • сохраненной копии игры оборудования Sharkport, являющегося предшественником PlayStation 2;
  • трехмерной модели различных категорий промышленных станков и агрегатов, спроектированной в автоматизированном программном комплексе FeatureCAM.

Другие похожие форматы и расширения файлов

Benefits

The benefit of memory mapping a file is increasing I/O performance, especially when used on large files. For small files, memory-mapped files can result in a waste of slack space as memory maps are always aligned to the page size, which is mostly 4 KiB. Therefore, a 5 KiB file will allocate 8 KiB and thus 3 KiB are wasted. Accessing memory mapped files is faster than using direct read and write operations for two reasons. Firstly, a system call is orders of magnitude slower than a simple change to a program’s local memory. Secondly, in most operating systems the memory region mapped actually is the kernel’s page cache (file cache), meaning that no copies need to be created in user space.

Certain application-level memory-mapped file operations also perform better than their physical file counterparts. Applications can access and update data in the file directly and in-place, as opposed to seeking from the start of the file or rewriting the entire edited contents to a temporary location. Since the memory-mapped file is handled internally in pages, linear file access (as seen, for example, in flat file data storage or configuration files) requires disk access only when a new page boundary is crossed, and can write larger sections of the file to disk in a single operation.

A possible benefit of memory-mapped files is a «lazy loading», thus using small amounts of RAM even for a very large file. Trying to load the entire contents of a file that is significantly larger than the amount of memory available can cause severe thrashing as the operating system reads from disk into memory and simultaneously writes pages from memory back to disk. Memory-mapping may not only bypass the page file completely, but also allow smaller page-sized sections to be loaded as data is being edited, similarly to demand paging used for programs.

The memory mapping process is handled by the virtual memory manager, which is the same subsystem responsible for dealing with the page file. Memory mapped files are loaded into memory one entire page at a time. The page size is selected by the operating system for maximum performance. Since page file management is one of the most critical elements of a virtual memory system, loading page sized sections of a file into physical memory is typically a very highly optimized system function.

Чем открыть файл в формате OBJ

Расширение OBJ может быть представлено тремя основными исполнениями:

Формат OBJ относится к типу файлов Wavefront 3D Object File и предназначен для обработки и хранения данных о трехмерной модели объекта. Являясь простым текстовым форматом представления данных, OBJ расширение может содержать весь набор параметрических данных, связанный с координатами вершин 3Д-объекта и положением его в пространстве, значением нормали к каждой из сторон, и любую другую информацию, которая имеет отношение к геометрическому представлению трехмерной модели.

Wavefront Technologies, являющийся официальным разработчиком OBJ расширения, предусмотрел хранение ссылки на файл MTL внутри формата. В MTL содержится набор структурированных данных, который дает представление о внешней геометрической форме объекта. MTL файл хранится в отдельном каталоге “Textures” и дополнительно может включать информацию о материале 3Д-модели.

OBJ – один из самых неприхотливых для импорта/экспорта форматов. Помимо стандартных систем автоматизированного проектирования (САПР) и многочисленных графических редакторов, визуализация трехмерной OBJ модели доступна и с использованием онлайн-ресурсов. В интернете собраны полномасштабные библиотеки 3Д-объектов в данном формате.

  • OBJ – объектно-ориентированный, модульный формат, предназначенный специально для программных приложений, функционирующих на базе микропроцессоре 80×86 Intel. Изначально, он назывался Object Module Format (объектно-модульный формат) и использовался на базе операционной системы MS-DOS. В таком виде OBJ расширение принято считать устаревшим.

Программы для открытия OBJ файлов

Если OBJ расширение представляет собой параметризованный набор данных о трехмерной модели объекта, для генерации и воспроизведения его на базе ОС Windows можно воспользоваться самыми разнообразными программными комплексами:

В данном представлении OBJ адаптирован и для платформы ОС Mac:

Если OBJ – объектно-ориентированный, модульный формат, его воспроизведение возможно исключительно в программных приложениях на платформе операционной системы MS-DOS, функционирующей на базе устаревшего микропроцессора 80×86 Intel.

OBJ файлы в Microsoft Visual Studio генерируются автоматически и используются в качестве вспомогательных для преобразования COFF и OMF. Какое-либо редактирование формата бывает востребовано крайне редко.

Если при открытии расширения OBJ возникает ошибка, причины могут заключаться в следующем:

  • поврежден или инфицирован файл;
  • файл не связан с реестром ОС (выбрано некорректное приложение для воспроизведения или не произведена инсталляция конкретного плагина);
  • недостаточно ресурсов устройства или ОС;
  • поврежденные или устаревшие драйвера.

Конвертация OBJ в другие форматы

Уникальная структура и область применения OBJ для случаев, когда формат представляет собой вспомогательный файл Microsoft Visual Studio или объектно-ориентированный, модульный файл для микропроцессора 80×86 Intel, не предоставляют возможностей для каких-либо конвертаций данного расширения.

Попытки конвертации расширения в другой формат могут не только не дать никаких практических результатов, но и повредить исходный файл. В этой связи трансляция данного формата практически не практикуется.

Исключение составляет, пожалуй, случай, когда OBJ — файл, содержащий данные о трехмерных координатах объекта.

Благодаря данным конверторам доступно преобразование OBJ в самые разнообразны форматы, включая STEP, STL, PRT, IGS, 3DS.

Почему именно OBJ и в чем его достоинства?

OBJ формат имеет три различных представления:

  • файл, содержащий параметризованный набор данных о трехмерной модели объекта;
  • объектно-ориентированный, модульный файл, адаптированный под устаревший микропроцессор 80×86 Intel;
  • вспомогательный файл, обеспечивающий корректную работу других форматов в программе Microsoft Visual Studio.

Расширение практически не востребовано в последних двух случаях.

Однако большую популярность формат приобрел у многочисленных компьютерных дизайнеров, конструкторов и проектировщиков трехмерных моделей изделий.

Без его наличия невозможна организованная запись геометрических параметров 3Д-объекта:

  • параметрических данных;
  • значения координат вершин 3Д-объекта;
  • положения 3D-модели в пространстве;
  • значения нормали к каждой из сторон 3Д-объекта;
  • текстуры координат.

Другие похожие форматы и расширения файлов

Overview

The classes , and provide access to memory-mapped files on Windows and POSIX systems. These behave much like the File Wrappers , and , with the following important differences:

  • By default, files must exist before being opened, and are not truncated; attempting to write past the end of a file results in an error. To map a file which does not yet exist, use .
  • Files are always opened in binary mode.
  • Wide-character streams are not supported.

Wide-character versions of the memory-mapped file Devices may be defined as follows, using the template :

    #include <boost/iostreams/code_converter.hpp>
    #include <boost/iostreams/device/mapped_file.hpp>

    typedef code_converter<mapped_file_source>  wmapped_file_source;
    typedef code_converter<mapped_file_sink>    wmapped_file_sink;
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector